c - C语言:从文件重定向输入时如何知道何时不再有来自标准输入的输入
问题描述
我的程序应该以下列方式运行:
CProgram <文件.txt
file.txt 可以有任意多的数据行。例如,
2 3 G 5 6
5 6 7
6 9 3 6 H
<<Blank line>>
有没有办法知道没有更多的输入行?每个文件的末尾都有一个空行。
我能够读取这些行,但我的程序永远不会知道是否没有更多数据要读取,并一直等待更多数据,因为它通常会从标准输入中得到。
这就是我的阅读方式
while( fgets(line, sizeof(line), stdin) != NULL) {
... do something
}
解决方案
当文件完成时,所有输入函数都会给你一个文件结束指示。例如:
#include <stdio.h>
int main(void) {
int count = 0;
while (getchar() != EOF)
++count;
printf("There were %d characters.\n", count);
return 0;
}
将计算输入流中的字符:
pax> ./testprog <testprog.c
There were 169 characters.
pax> echo -n hello | ./testprog
There were 5 characters.
如果您正在使用fgets
(从您的更新中可以看出),这也可以轻松检测:
#include <stdio.h>
static char buff[1000];
int main(void) {
int count = 0;
while (fgets(buff, sizeof(buff), stdin) != NULL)
++count;
printf("There were %d lines.\n", count);
return 0;
}
运行将计算行数:
pax> ./testprog <testprog.c
There were 12 lines.
在这两种情况下,您都可以看到使用输入重定向或管道方法正确检测到文件结尾。如果您正在运行从终端读取的代码,则只需使用环境提供的工具来指示文件结束。
这通常CTRL-D在类 UNIX 操作系统的行首,或者CTRL-Z在 Windows 的行首:
pax> ./testprog
this has
two lines
<Ctrl-D pressed (I run Linux)>
There were 2 lines.
推荐阅读
- python - 带有 boost/dll 的 pybind - 双重使用 DLL?
- python - df[column].mean() 返回一个浮点数,如何在 Python 中检查它是否不同于零?
- r - R命令(类,object.size)挂起
- azure - 尝试使用 azure terraform 在应用程序网关上附加 SSL 证书
- bash - VS Code - 通过 SSH 隧道打开文件夹和编辑文件
- spring - Spring Config Server - 如何访问每个环境中的文件夹内的文件?
- r - 如何在 ggplot 中绘制带有日期和时间轴的折线图?
- python - 图书馆会员课,不知道我哪里错了
- node.js - 启动 pm2 获取 module_conf.json 不存在时出错
- algorithm - 为什么splay树的摊销分析只关注splay操作而不考虑向下搜索