龟etc,检查EOF [英] fgetc, checking EOF
问题描述
在这本书的的Linux系统编程的我看过一些这样的:
龟etc
返回解读为unsigned char型
强制转换为INT 字符code>或
EOF
的文件或错误结束。使用龟etc
一个常见的错误是:字符℃;
如果((C =龟etc())!= EOF){...}这code的正确版本是:
INT℃;
(!(C =龟etc())= EOF){如果的printf(%C(字符)C); ...}
块引用>那么,为什么我不能用
EOF
比较之前蒙上了返回值字符
?我为什么要比较EOF
正好与INT
?由于EOF
定义为1
,是不是通常铸造到字符
?结果是否有平台/编译器它是不是真的?解决方案呦无法将返回值转换为char,因为返回值可以是
EOF
和EOF
值是系统相关的,不等于任何有效的字符code。 链接通常它是
1
,但你不应该假定。检查从 C-FAQ-网站这个伟大的答案:
两种失效模式是可能的,如果作为在片段上方的getchar的
返回值被分配给一个字符。
如果char类型是有符号的,如果EOF被定义(像通常那样)为-1时,
字符与十进制值255('\\ 377'或'\\ XFF'在C)将
符号扩展将相当于EOF,prematurely终止
输入。 (假设8位字符)。
如果char型无符号,实际值EOF将被截断(由
具有其高位比特丢弃,可能导致255或
0xff的)而不会被识别为EOF,从而有效地
无限输入。
块引用>希望它帮助!
编辑:(加入这个答案@FatalError评论,这是在C-FAQ网站解释,但这看起来更清楚我)
如果你将它转换成char然后EOF采用相同的值作为一些有效的字符,因此成为从角色没有区别。这本身就应该是足够的理由不使结果的字符@FatalError评论。
In the book Linux System Programming I have read some like this:
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); ... }
So, why can't I cast a return value to
char
before comparing withEOF
? Why do I have to compareEOF
exactly withint
? AsEOF
defined as-1
, isn't it normally casted tochar
?
Are there platforms/compilers where it is not true?解决方案Yo can not cast the return value to char because the return value could be
EOF
, andEOF
value is system-dependent and is unequal to any valid character code. linkUsually it is
-1
but you should not assume that.Check this great answer from the 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.
Hope it helps!
Edited: (added the @FatalError comment on this answer, this is explained on the c-faq site but this looks more clear to me)
"If you cast it to char then EOF takes the same value as some valid character and hence becomes indistinguishable from that character. That alone should be enough justification to not make the result a char" @FatalError comment.
这篇关于龟etc,检查EOF的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!