问题
fgetc() function reads characters from a text file in Ubuntu.
the last character before EoF is with code = -1.
what the heck is that? in text editor file seems ok, no strange symbols at end.
while (!feof(fp))
{
c = fgetc(fp);
printf("%c %i\n", c, c);//
}
回答1:
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?.
来源:https://stackoverflow.com/questions/34245695/fgetc-reads-character-with-value-1