fscanf() outputs the wrong value

Viewed 61

I am trying to read integers from a text file. However this code keeps endlessly printing the value of i. So it keeps printing zeros instead of the integers in the file. How do I fix this? Thank you!

FILE* inFile = fopen(filename,"r");
    int i=0;
    int x;


    while(fscanf(inFile,"%d",&i)!= EOF){
            printf("%d\n", i);
            usleep(30000);
            //fscanf(inFile,"%d",&i);

    }
    fclose(inFile);
1 Answers

fscanf() returns the number of fields successfully scanned.

So rather than

while (fscanf(inFile, "%d", &i) != EOF)

try something like

while (fscanf(inFile, "%d", &i) == 1)
Related