October 21, 2024
Chicago 12, Melborne City, USA
C#

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


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:

0,4
0,6
0,9
0,10
1,5
1,7
1,9
2,6
2,8
2,10
3,4
3,7

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 a 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?

Edit: Here is the minimal working example that I tried after seeing some answers below.

#include <stdio.h>

int main(){
    FILE *file_ptr_edges;
    file_ptr_edges = fopen("myfile.dat", "r");
    int u, v, eof;
    int r = 1;
    while (r != EOF){
        r = fscanf(file_ptr_edges, "%d,%d\n", &u, &v);
        printf("u = %d,v = %d\n", u, v);
        printf("%d\n", r);
    }
    fclose(file_ptr_edges);

    return 0;
}

Output:

u = 0,v = 4
2
u = 0,v = 6
2
u = 0,v = 9
2
u = 0,v = 10
2
u = 1,v = 5
2
u = 1,v = 7
2
u = 1,v = 9
2
u = 2,v = 6
2
u = 2,v = 8
2
u = 2,v = 10
2
u = 3,v = 4
2
u = 3,v = 7
2
u = 3,v = 7
-1

Thus r seems to take value -1 when the last line is reached. This solves my problem although I don’t understand how the values of r are changing.



You need to sign in to view this answers

Leave feedback about this

  • Quality
  • Price
  • Service

PROS

+
Add Field

CONS

+
Add Field
Choose Image
Choose Video