Home > Enterprise >  Read a file with unknown number of lines in C using fscanf
Read a file with unknown number of lines in C using fscanf

Time:05-01

I tried to search for the answer here and elsewhere on the Internet, but didn't get exactly what I am looking for. I have a data file that looks like this:

enter image description here

I can read this file line by line using fscanf without any issue. However, I don't know the number of lines in the file. I tried using the for loop with a very large number of iterations:

int u, v;
FILE *ptr = fopen("myfile.dat", "w");
for (int i=0; i < 1000000;   i){
    fscanf(ptr, "%d,%d\n", &u, &v);
}
fclose(ptr);

However, this keeps repeatedly reading the last line of the file after previous lines are read. Why does this happen? And how do I correctly address my problem so that I would be able to read a file with unknown number of lines correctly?

CodePudding user response:

You need to check the result of fscanf (and every other standard library function you call that returns a result).

The fscanf function returns the value of the macro EOF if an input failure occurs before the first conversion (if any) has completed. Otherwise, the function returns the number of input items assigned, which can be fewer than provided for, or even zero, in the event of an early matching failure.

Something like this should work:

while (fscanf(ptr, "%d,%d\n", u, v) == 2) {
   // do something with the numbers
}
if (feof(stdin)) {
   // the file was read to the end
} else {
   // there was an error
   perror ("Could not read the input");
}

Also, please read A beginners' guide away from scanf().

CodePudding user response:

You need to terminate your loop when fscanf() returns EOF (end of file):

int r = fscanf(ptr, "%d,%d\n", &u, &v);
if(r == EOF) break;

Note, u is only valid for r > 0 and v for r == 2. I don't know what behavior you want for r == 0 or r == 1.

  • Related