在 Linux System Programming 这本书中,我读过一些这样的书:
fgetc
returns the character read as anunsigned char
cast to anint
orEOF
on end of file or error. A common error usingfgetc
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
?为什么我必须将 EOF
与 int
进行精确比较?由于 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.
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).
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/