首页 > 解决方案 > Linux C IO 问题:ctrl+D 一次还是两次?

问题描述

测试1.c

#include <stdio.h>

int main(void)
{
    int ch;
    FILE *fp;
    fp = fopen("file1.txt", "w");

    while ((ch = fgetc(stdin)) != EOF)
    {
        fputc(ch, fp);
    }

    printf("\n");

    return 0;
}

测试2.c

#include <stdio.h>

int main(void)
{
    int ch;

    while ((ch = fgetc(stdin)) != EOF)
    {
        fputc(ch, stdout);
    }

    printf("\n");

    return 0;
}

这两个文件之间的区别在于while循环中的表达式(一个输出到文件,而另一个输出到stdout)。

两个程序的行为让我感到困惑。

test1.c:我应该输入两次 ctrl+D 来完成我的输入。例如我输入“123 ctrl+D ctrl+D”,第一个 fgetc 返回和 while 循环运行,最后 ch 可以让 EOF 用完 while 循环。

test2.c:当我只输入一次 ctrl+D 时 fgetc 返回。例如“123 ctrl+D”,fgetc 返回,while 循环运行,但 ch 无法获取 EOF,因此被最后一个 fgetc 阻塞。

为什么?

我的环境:

gcc (Ubuntu 7.4.0-1ubuntu1~18.04.1) 7.4.0
Linux ubuntu 4.15.0-76-generic #86-Ubuntu SMP x86_64 GNU/Linux

标签: clinuxubuntugccglibc

解决方案


推荐阅读