首页 > 解决方案 > 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
}

标签: cgccc11

解决方案


当文件完成时,所有输入函数都会给你一个文件结束指示。例如:

#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.

推荐阅读