gpt4 book ai didi

c - stdin 允许读取 EOF 标志集

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

在我的平台上,下面的代码允许我成功地从 stdin 中读取,即使它的文件结束标志被设置,它在读取后也保持设置。要重现该行为,首先键入文件结束快捷方式(Ctrl+D 在 Unix 上,Ctrl+Z 在 Windows 上),然后键入一个普通字符。

#include <stdio.h>

// first type the shortcut for EOF, then a single character

int main(void) {
getchar();
printf("feof(stdin): %s\n", feof(stdin) ? "true" : "false");
int ch = getchar();
if (ch == EOF) return 0;
printf("%c\n", (char) ch);
printf("feof(stdin): %s\n", feof(stdin) ? "true" : "false");
}

我得到的输出(在输入字母 f 之后):

feof(stdin): true
f
feof(stdin): true

来自 C11 标准(7.21.7.1,fgetc 函数,3):

Returns

If the end-of-file indicator for the stream is set, or if the stream is at end-of-file, the end-of-file indicator for the stream is set and the fgetc function returns EOF

getchar() 等同于 getc(stdin) (7.21.7.6),后者又是 fgetc(stdin) 的宏> (7.21.7.5)。所以 getchar() 的行为应该与 fgetc(stdin) 完全一样。

在我看来,这不符合标准。我错过了什么吗?


这个问题之前提到了C++(因此在评论中讨论了很长时间),但是这个问题可以缩小到C标准库,所以我编辑了。以下信息可能仍然是相关的:

平台之间的行为不一致:

  • Arch Linux、GCC 7.3.1:可以在 EOF 后读取;
  • Windows 7,GCC(Rev1,由 MSYS2 项目构建)7.2.0:可以在 EOF 后读取;
  • MacOS High Sierra、Apple LLVM 版本 9.0.0 (clang-900.0.39.2):无法在 EOF 后读取;
  • FreeBSD 10.3、clang 3.4.1 和 GCC 5.4.0:无法在 EOF 后读取。

这个问题是this one的后续问题,这是关于 cin.clear() 似乎没有取消设置 stdin 的文件结束标志的事实,经过一些有用的评论和聊天讨论。

最佳答案

在 Linux 上,这确实是 st​​dio 实现中的一个已知 glibc 错误:#1190 - from 2005 , #19476 - duplicate from 2016仅在最近的 2.28 版本中得到修复。

关于c - stdin 允许读取 EOF 标志集,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49896165/

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