c - fgetc,检查 EOF

标签 c eof fgetc

Linux System Programming 这本书中,我读过一些这样的书:

fgetc returns the character read as an unsigned char cast to an int or EOF on end of file or error. A common error using fgetc is:

char c;
if ((c = fgetc()) != EOF) {...}

The right version of this code is:

int c;
if ((c = fgetc()) != EOF) { printf("%c", (char)c); ... }

那么,为什么我不能在与 EOF 比较之前将返回值转换为 char?为什么我必须将 EOFint 进行精确比较?由于 EOF 定义为 -1,它不是通常被转换为 char 吗?
有平台/编译器吗?真的吗?

最佳答案

不能将返回值转换为 char,因为返回值可能是 EOF,而 EOF 值是系统相关的,不等于任何有效的字符代码. link

通常它是 -1 但您不应该这样假设。

查看来自 c-faq-site 的出色答案:

Two failure modes are possible if, as in the fragment above, getchar's return value is assigned to a char.

  1. If type char is signed, and if EOF is defined (as is usual) as -1, the character with the decimal value 255 ('\377' or '\xff' in C) will be sign-extended and will compare equal to EOF, prematurely terminating the input. (assuming 8 bits char).

  2. If type char is unsigned, an actual EOF value will be truncated (by having its higher-order bits discarded, probably resulting in 255 or 0xff) and will not be recognized as EOF, resulting in effectively infinite input.

希望对您有所帮助!

已编辑:(在这个答案上添加了@FatalError 评论,这在 c-faq 网站上有解释,但这对我来说看起来更清楚)

“如果将其转换为 char,则 EOF 将采用与某个有效字符相同的值,因此与该字符无法区分。仅此一项就足以证明不会将结果设为 char”@FatalError 评论。

关于c - fgetc,检查 EOF,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11057259/

相关文章:

c - cygwin 中混合 C/FORTRAN 程序的共享内存处理

c - 从 C 中的文件扫描

c++ - std::getline 在遇到 eof 时抛出

c - 带有 EOF 的 bool 表达式不起作用

c - fget(c) - 在保存前一个字符的同时扫描下一个字符

c - 为什么 fgetc() 返回 int 而不是 char?

c - 为什么 fgetc 在 C 中只能读取 PNG 的某个字节?

代码永远不会被执行 C

c - 测试整数时 sscanf() 无法正常工作

C: 编译器警告 "return discards qualifiers from pointer target type"