gpt4 book ai didi

c - 在 int width == CHAR_BIT 的特殊情况下,fgetc 的输出是什么

转载 作者:太空宇宙 更新时间:2023-11-04 03:03:51 25 4
gpt4 key购买 nike

在 C99 的 7.19.7.1 节中,我们有:

If the end-of-file indicator for the input stream pointed to by stream is not set and a next character is present, the fgetc function obtains that character as an unsigned char converted to an int and advances the associated file position indicator for the stream (if defined).

据我了解,int 类型可以与 unsigned char 具有相同的宽度。在这种情况下,我们是否可以得出结论,只有 int width > CHAR_BIT 时,fgetc 才能正常运行。

(引用 blagovest 的评论),C99 是否指定何时需要标准库,或者符合标准的实现是否可以实现部分而非全部标准库?

最佳答案

fgetc返回 EOF在文件结束或错误情况下。

否则,它返回读取的字符,作为 unsigned char , 转换为 int .

假设 CHAR_BIT == 16sizeof (int) == 1 ,并假设读取的下一个字符的值为 0xFFFF。然后 fgetc()将返回 0xFFFF 转换为 int .

这里有点棘手。由于 0xFFFF 不能用 int 类型表示,转换的结果是实现定义的。但通常情况下,结果将为 -1,这是 EOF 的典型值(事实上,这是我听说过的唯一值)。 .

所以在这样的系统上,fgetc()可以回EOF即使它成功读取了一个字符。

这里没有矛盾。标准保持fgetc()返回 EOF在文件末尾或出错时。它并没有说相反;返回 EOF 不一定暗示存在错误或文件结束条件。

您仍然可以确定是否 fgetc()通过调用 feof() 读取或不读取实际字符和 ferror() .

所以这样的系统会打破典型的输入循环:

while ((c = fgetc()) != EOF) {
...
}

但它不会(必然)不符合标准。

(with reference to the comment by blagovest), does C99 specify when the standard library is to be expected, or whether a conforming implementation can implement part but not all of the standard library?

“托管实现”必须支持整个标准库,包括 <stdio.h> .

“独立实现”不需要支持 <stdio.h> ;仅不声明任何函数的标准 header ( <limits.h><stddef.h> 等)。但是独立的实现可能会提供 <stdio.h>如果它选择。

通常独立的实现是针对嵌入式系统的,通常没有操作系统。

实际上,我所知道的每个当前托管实现都有 CHAR_BIT==8 .这意味着在实践中你可以可能指望EOF结果来自 fgetc()实际上指示文件结束或错误——但标准并不保证这一点。

关于c - 在 int width == CHAR_BIT 的特殊情况下,fgetc 的输出是什么,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8134054/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com