#include <stdio.h>
#define MAXLINE 4096
int
main(int argc, char **argv)
{
char *s;
char buf[MAXLINE];
s = fgets(buf, MAXLINE, stdin); // here, if replaced with read(0, buf, MAXLINE);
return 0;
}
输入是:12ctrl+d
fgets
直到再次输入 ctrl+d(即:12ctrl+dctrl+d
)才会返回。为什么 fgets 在遇到第一个EOF
时不返回? 似乎 12ctrl+d
不起作用。但是当
s = fgets(buf, MAXLINE, stdin);
被替换为read(0, buf, MAXLINE);
read
会返回(输入也是:12ctrl+d
)。
最佳答案
Hitting CTRL+d on the terminal:
- simply means flush all the characters in
stdin
(the input buffer) immediately- it does NOT trigger an EOF condition on
stdin
(unless the current line/buffer is co-incidentally empty.)
所以在运行程序时按 CTRL+D,
- 如果您连续执行两次,阻塞的
fgetc()
将返回。
1st = 刷新当前缓冲的字符,
2nd = 刷新空缓冲区;即EOF
条件对fgetc()
有效并返回。 - 如果您在空行上执行一次,阻塞的
fgetc()
将返回。
刷新一个已经空的stdin
缓冲区,即EOF
条件对fgetc()
有效并返回。< - 阻塞的
read()
在输入被刷新后立即返回。
查看此 question 的答案了解更多详情。
关于c - 为什么 EOF 在 fgets 和 read 中的行为不同,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35536586/