简体   繁体   English

在C语言的重定向输入文件中查找文件末尾

[英]Finding End of File in the Redirected Input file in C

I execute my program from shell like that : 我像这样从shell执行程序:

$main.exe < input.txt

in input.txt I have digits (Count of these digits is unknown) 在input.txt中我有数字(这些数字的计数未知)

in my program I doing something like : 在我的程序中,我做类似的事情:

while(1)
{

int xCoordinate, yCoordinate;
scanf("%d %d", &xCoordinate, &yCoordinate);

......

}

How can I break this loop when there is no value to read? 当没有值要读取时,如何中断此循环?

Assuming that the input is consistent, you can do it like this: 假设输入是一致的,您可以这样做:

if (scanf("%d %d", &xCoordinate, &yCoordinate) != 2) break;

The reason this would work is that scanf family of functions return the number of entries that they assigned. 之所以可行,是因为scanf系列函数返回了它们分配的条目数。 In your code, you want scanf to assign two items; 在您的代码中,您希望scanf分配两个项目。 if EOF is reached instead, a value smaller than 2 would be returned. 如果改为达到EOF,则将返回小于2的值。

Note: that this approach will break at the first spot where the input file is not consistent with the format that you expect. 注意:这种方法将在输入文件与您期望的格式不一致的第一点中断。 For example, if your input has a string in place of one of the numbers, the loop would exit after making a failed attempt to interpret that string as a number. 例如,如果您输入的字符串代替数字之一,则在尝试将该字符串解释为数字失败后,循环将退出。

You have to separate the "reading from a file (or stdin)" from the "parsing the line I read. You will get terribly wrong answers if the data is not perfectly what you expect. 您必须将“读取文件(或stdin)”与“解析我读取的行”分开。如果数据不完全符合您的期望,您将得到非常错误的答案。

You get fine control with something like 您可以通过以下方式很好地控制

char buffer[BUFSIZ];
int xCoordinate, yCoordinate;

while(fgets(buffer, BUFSIZ, stdin) != NULL) {
    if(sscanf(buffer, "%d %d", &xCoordinate, &yCoordinate) != 2) {
        fprintf(stderr, "parsing error\n")
        exit(1);
    }
}

Even this leaves a bit to be desired because if fgets returns NULL it can either mean EOF or "read error" but it is far more robust than scanf and keeps to the spirit of the original. 即使这样,仍然有一点不足之处,因为如果fgets返回NULL,则可能表示EOF或“读取错误”,但它比scanf健壮得多,并且保持原始格式。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM