0

I'm using feof() C function to know whether I am at the end of my file or not, but it seems that it never returns -1 even when I reach the end of the file..

here is what I do :

do {
       j+= fscanf(base, "%f %f %f %d", &a, &b, &c, &d);
       another stuff here....

}while(!feof(file))

I notice that it doesen't work as I have another condition which is if(j!=4) then signal a problem, my file is all good, the problem is that when it's finished I still go in another iteration which cause j = -4 as nothing can be read and my error occures..

Any ideas ? Thank you all !

  • If the input does not match the format string, then `fscanf` will not progress and you will never get to the end of the stream. – William Pursell Mar 27 '20 at 21:13
  • Note that `feof()` returns zero when EOF is not reached, and some non-zero value (not necessarily, or usually, `-1`) when EOF has been reached. – Jonathan Leffler Mar 27 '20 at 21:24
  • 1
    The `j += fscanf(…);` notation is surprising. Normally, you'd use a plain assignment `j = fscanf(…);` to get the current operation's result. And your whole loop should probably be `while ((j = fscanf(…)) == 4) { … }` — avoiding the need for `feof()` etc (though it would be legitimate to check its value after the loop to distinguish between early exit because of a format error and actual EOF. The assignment to `j` in the loop control is optional; you probably don't need it unless something goes wrong and you get 0, 1, 2, or 3 in it instead of 4 or EOF. – Jonathan Leffler Mar 27 '20 at 21:28
  • yes indeed, actually I'm doing j = ... not += sorry for the typo in the post ! – Mehdi Zayene Mar 28 '20 at 22:03
  • And okay I see! thank you very much ! – Mehdi Zayene Mar 28 '20 at 22:05

0 Answers0