龟etc,检查EOF [英] fgetc, checking EOF

查看:102
本文介绍了龟etc,检查EOF的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在这本书的的Linux系统编程的我看过一些这样的:


  

龟etc 返回解读为 unsigned char型强制转换为 INT
   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的
  返回值被分配给一个字符。


  
  

      
  1. 如果char类型是有符号的,如果EOF被定义(像通常那样)为-1时,
      字符与十进制值255('\\ 377'或'\\ XFF'在C)将
      符号扩展将相当于EOF,prematurely终止
      输入。 (假设8位字符)。


  2.   
  3. 如果char型无符号,实际值EOF将被截断(由
      具有其高位比特丢弃,可能导致255或
      0xff的)而不会被识别为EOF,从而有效地
      无限输入。


  4.   

希望它帮助!

编辑:(加入这个答案@FatalError评论,这是在C-FAQ网站解释,但这看起来更清楚我)

如果你将它转换成char然后EOF采用相同的值作为一些有效的字符,因此成为从角色没有区别。这本身就应该是足够的理由不使结果的字符@FatalError评论。

In the book Linux System Programming I have read some like this:

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); ... }

So, why can't I cast a return value to char before comparing with EOF? Why do I have to compare EOF exactly with int? As EOF defined as -1, isn't it normally casted to char?
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, and EOF value is system-dependent and is unequal to any valid character code. link

Usually 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.

  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.

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆