c - 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
解决方案
推荐阅读
- reactjs - 如何添加多个图像并使用 react 和 express 预览它们?
- node.js - nodejs中AWS lambda上的哨兵不发送异常
- python - 如何将一个函数的输出用作另一个函数的参数
- python - numpy 修复内存利用率问题 MemoryError not using all available 120gb of RAM but still throw an error
- delphi - 有没有办法根据具体情况选择具体的案例陈述?
- html - 如何创建并排的 HTML 表格网格?
- json - 以人类可读格式从响应 JSON 转换日期和时间
- java - 使用可变运行时间估计剩余时间
- php - PHPSpreadsheet - 如何创建一个额外的选项卡?
- apache-spark - _spark_metadata 目录有什么用