这个例子来自K&R书
#include<stdio.h>
main()
{
long nc;
nc = 0;
while(getchar() != EOF)
++nc;
printf("%ld\n", nc);
}
您能解释一下为什么会这样吗?谢谢。
^Z^Z 也不起作用(除非它在一行的开头)
最佳答案
tty 的传统 UNIX 解释 EOF
八字是做堵read
读取熟 tty 行缓冲区中缓冲的内容后返回。在新行的开头,表示 read
返回 0(读取零字节),顺便说一下,大小为 0 的 read
是如何检测普通文件的文件结束条件。
这就是为什么第一个 EOF
在一行的中间只是强制行的开头是 read
,不让 C 运行时库检测到文件结尾。 两个 EOF
一行中的字符产生 0 大小的读取,因为第二个字符强制空缓冲区为 read
通过应用程序。
$ cat
foo[press ^D]foo <=== after ^D, input printed back before EOL, despite cooked mode. No EOF detected
foo[press ^D]foo[press ^D] <=== after first ^D, input printed back, and on second ^D, cat detects EOF
$ cat
Some first line<CR> <=== input
Some first line <=== the line is read and printed
[press ^D] <=== at line start, ^D forces 0-sized read to happen, cat detects EOF
我假设您的 C 运行时库模仿上述语义(在 Windows 上,在 ^Z
调用级别没有对 kernel32
的特殊处理,更不用说系统调用了)。这就是为什么它可能会在 ^Z^Z
之后检测到 EOF。即使在输入行的中间。
关于c - 为什么 getchar() 只在一行的开头识别 EOF?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14436596/