Berke Cagkan Toptas
Berke Cagkan Toptas

Reputation: 1034

Finding End of File in the Redirected Input file in C

I execute my program from shell like that :

$main.exe < input.txt

in input.txt I have digits (Count of these digits is unknown)

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?

Upvotes: 0

Views: 1015

Answers (2)

msw
msw

Reputation: 43497

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.

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.

Upvotes: 1

Sergey Kalinichenko
Sergey Kalinichenko

Reputation: 726599

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. In your code, you want scanf to assign two items; if EOF is reached instead, a value smaller than 2 would be returned.

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.

Upvotes: 3

Related Questions