feof
is meant to signal that you’ve tried to read past the end of file – which means that you first have to reach it. So it will only work after you try to read and the system realizes you’re at the end. And what does fgetc
return if you try to read past the end of file? EOF
(conveniently, -1
– which is why fgetc
returns an int
instead of a char
).
So what’s happening is that you enter the loop – because you haven’t yet tried to read past at the end yet – and call fgetc
which returns -1 because you tried to read past the end of the file. The next time around the loop, feof
tells you that you’ve already hit the end of the file and tried to read past it and you break out.
You should read the documentation of functions you intend to use: feof
and fgetc
documentation explain this. But even if they did not, a simple google search would have answered your question: Why is “while ( !feof (file) )” always wrong?.
2
solved fgetc reads character with value = -1