C语言 fgetc():只检查EOF就够了吗?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4292729/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
fgetc(): Is it enough to just check EOF?
提问by helpermethod
In various examples found on the web fgetc()is used like this:
在网络上找到的各种示例中,fgetc()是这样使用的:
FILE *fp = fopen(PATH, "r");
if (fp == NULL) {
perror("main");
exit(EXIT_FAILURE);
}
int ch;
while (ch = fgetc(fp) != EOF) {
// do something
}
But according to the manpage to fgetc()
但是根据 fgetc() 的联机帮助页
If a read error occurs, the error indicator for the stream shall be set, fgetc() shall return EOF, [CX] and shall set errno to indicate the error.
如果发生读取错误,则应设置流的错误指示符,fgetc() 应返回 EOF、[CX] 并应设置 errno 以指示错误。
So need I check this too? And how?
所以我也需要检查一下吗?如何?
采纳答案by terminus
You can check it with ferror(3), right after the while:
您可以使用 ferror(3) 进行检查,紧接着之后:
while (EOF != (ch = fgetc(fp)))
// do something
if (ferror(fp) != 0)
// error handling
ferror returns a non-zero if an error occured.
如果发生错误,ferror 返回非零值。
If you want use fp after an error occured, you'll need to clear the error flag with clearerr:
如果您想在发生错误后使用 fp,则需要使用 clearerr 清除错误标志:
clearerr(fp);
回答by casablanca
This is what the specs say:
这是规范所说的:
the fgetc() function shall obtain the next byte as an unsigned char converted to an int
The following macro name shall be defined as a negative integer constant expression: EOF
fgetc() 函数将获取下一个字节作为转换为 int 的无符号字符
以下宏名称应定义为负整数常量表达式:EOF
As long as you store the return value in an intand not a char, it is sufficient to check for EOFbecause it is guaranteed not to represent a valid character value.
只要您将返回值存储在 anint而不是 a 中char,就足以进行检查,EOF因为它保证不代表有效的字符值。
Also, in your code, this:
另外,在你的代码中,这个:
while (ch = fgetc(fp) != EOF)
should be:
应该:
while ((ch = fgetc(fp)) != EOF)
The additional parentheses are required because !=has higher precedence than =.
额外的括号是必需的,因为!=它的优先级高于=。
回答by R.. GitHub STOP HELPING ICE
Looping until fgetcreturns EOFis perfectly fine. Afterwards, if you want to know whether the loop ended due to simply reaching the end of the file or due to an error, you should call ferroror feof. If you don't care you can skip the call.
循环直到fgetc返回EOF完全没问题。之后,如果您想知道循环是由于简单地到达文件末尾还是由于错误而结束,您应该调用ferror或feof。如果你不在乎,你可以跳过这个电话。
Note that it matters whether you check feofor ferror, because the error indicator for a stream is sticky and can evaluate true even when hitting eof was the cause of fgetcfailure. Normally you should use feofto check, and if it returns false, conclude that the loop stopped due to a new error.
请注意,是否检查feof或很重要ferror,因为流的错误指示符是粘性的,并且即使在命中 eof 是fgetc失败的原因时也可以评估为 true 。通常您应该使用feof来检查,如果它返回 false,则断定循环由于新错误而停止。

