fgetc reads character with value = -1

谁说胖子不能爱 提交于 2019-12-13 09:49:29

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!