c - 为什么 EOF 在 fgets 和 read 中的行为不同

标签 c linux fgets eof

#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

  1. fgets 直到再次输入 ctrl+d(即:12ctrl+dctrl+d)才会返回。为什么 fgets 在遇到第一个 EOF 时不返回? 似乎 12ctrl+d 不起作用。

  2. 但是当 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/

相关文章:

c - 显示字符串中每个字符的二进制

linux - 如何从 arptables 发送 arp 数据包到队列

c - 如何从文本文件存储 STDIN

c - Fgets 跳过输入并打印下一行?

c - 为什么 strtok(line, "\n") **不** 用于去除 fgets() 留下的换行符

c - 在(选择)聊天客户端上接收消息延迟

c - Int 到 Binary 转换说明

c - 如何释放这段 C 代码中分配的内存?

linux - 使用 sed 删除每个单词上某个字符后的所有内容

linux - Ngrep 多个 pcaps