Home>

a.txt contains data with multiple rows and 2 columns.
First, I want to read the file, get the number of lines, and store the matrix in a two-dimensional array.
I made a 2D array with a for statement, but the output does not work.
I'm new to c language. If anyone knows, please let me know ...

include define BUF_SIZE 256

int main (int argc, char * argv [])
{
FILE * fp;
char buf [BUF_SIZE];
int line = 0;
if ((fp = fopen ("a.txt", "r")) == NULL) {
return -1;
}
while (fgets (buf, BUF_SIZE, fp)! = NULL) {
line ++;
}
printf ("% d \ n", line);// Line count output

int i, j, val [line] [2];
for (i = 0;i for (j = 0;j<2;j ++) {
fscanf (fp, "% d",&val [i] [j]);
}
}

for (i = 0;i for (j = 0;j<2;j ++) {
printf ("% d", val [i] [j]);
}
printf ("\ n");
}

fclose (fp);
return 0;
}

c
  • Answer # 1

    Open the file (to find the number of lines)fgetsRead to the end
    Next timefscanfI'm doing it, but I can't read anything because it's already at the end of the file.

    Proposal 1: Oncefclosedo itfopenAfter re-doingfscanf(Easy to understand even for beginners)
    Proposal 2:rewindOrfseekTo return to the beginning of the file (need to understand the concept of a file position indicator for a file stream)

  • Answer # 2

    To write a code for a question, press thebutton and enter "code" from #incude
    Overwrite the code up to }. Overwrite C for "Enter language here".

    #include<stdio.h>
    #define BUF_SIZE 256
    int main (int argc, char * argv [])
    {
        FILE * fp;
        char buf [BUF_SIZE];
        int line = 0;
        if ((fp = fopen ("a.txt", "r")) == NULL) {
            return -1;
        }
        while (fgets (buf, BUF_SIZE, fp)! = NULL) {
            line ++;
        }
        printf ("% d \ n", line);// Output the number of lines
        rewind (fp);// ★ or fseek (fp, 0, SEEK_SET);
        int i, j, val [line] [2];
        for (i = 0;i<p></pre>
    <p><br />
    a.txt</p>
    <pre><code data-language = "Plain text">110000528 110000031
    110000529 110000059
    110000033 110000531
    110000031 110000062


    Execution result

    Four
    110000528110000031
    110000529110000059
    110000033110000531
    110000031110000062

  • Answer # 3

    while (fgets (buf, BUF_SIZE, fp)! = NULL) {
    line ++;
    }

    You're probably giving the number of lines, which causes the file pointer to point to the end of the file.
    This next fscanf will always fail because it reads the end of the file
    You need to reset the file pointer to the beginning, right?

  • Answer # 4

    the first

    while (fgets (buf, BUF_SIZE, fp)! = NULL) {

    So, the read position from the file is the end of the file. Therefore, it cannot be read by the next fscanf ().

    There are several ways,fseek (fp, 0, SEEK_SET);Then, return the file position to the beginning of the file, or for the line data read by buf,sscanf ()Is it read by or around that?