2

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);
  • 2
    Why are you not instead looping while the return value is 1? Note that the return value is only EOF, if the end of the file stream was encountered. If some other argument matching error occurred in this context, the return value would be 0. – paddy Oct 10 '19 at 23:51
  • 1
    Because you'll need to know this eventually, [Why is iostream::eof inside a loop condition (i.e. `while (!stream.eof())`) considered wrong?](https://stackoverflow.com/questions/5605125/why-is-iostreameof-inside-a-loop-condition-i-e-while-stream-eof-cons) – user4581301 Oct 11 '19 at 00:15

1 Answers1

3

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)
Sid S
  • 5,887
  • 2
  • 12
  • 23
  • Okay, I'll change the guard then. What about it printing the value of i instead of the integer read from the file? – Denis Shevchenko Oct 10 '19 at 23:56
  • 2
    That's a side-effect of the input failing, and `i` not being modified. If you have non-integer text in the file, this will happen. It's also possible that the file was not even opened. You never actually tested that `fopen` succeeded. – paddy Oct 10 '19 at 23:58
  • I figured it out. Thank you so much. – Denis Shevchenko Oct 11 '19 at 00:04