Agrudge Amicus
Agrudge Amicus

Reputation: 1103

setting input stream to return EOF repeatedly in loop

I have written this:

#include<stdio.h>

int main(void)
{
    int input=0;

    while(input=getchar())               //TARGET
        printf("%d\n",input);
}

I have intentionally used loop without !=EOF. And I am asking about what bit is set after pressing ctrl+d as it keeps printing -1 even without entering any input - indicating that some error bit must've been set for the stream which is making getchar() return -1 repeatedly - I want to know what that is. & what is going behind this entire thing.

Plus how to reset the stream to a normal state again.

It is an input on linux.

Upvotes: 3

Views: 290

Answers (2)

Barmar
Barmar

Reputation: 781096

The stream's end-of-file flag is set when it reaches EOF. This is the flag that the feof() function tests.

If you want to read past this, you can use the clearerr() function. This clears both the error and EOF indicators (I don't think there's a way to clear just one of them).

int main(void)
{
    int input=0;

    while(input=getchar()) {              //TARGET
        printf("%d\n",input);
        if (feof(stdin) || ferror(stdin)) {
            clearerr(stdin);
        }
    }
}

Note that whether you actually can read anything after EOF is both system- and device-dependent. If stdin is a terminal or ordinary file, EOF is a temporary condition (the user can keep typing on the terminal after entering Ctl-d, and more data can be added to a file). But once you get to the end of a TCP stream, nothing can be added to it.

Upvotes: 7

Schien
Schien

Reputation: 3903

I have tested a clone of your snippet in several environments. First of all, the Ctrl+D does not always emulate an EOF. In Windows it is Ctrl+Z. A reliable way to test is to use a redirect:

test.exe < sample.txt

Without this, in the "interactive mode", you can see the difference between the following:

a a a Ctrl+Z 97 97 97 10 (10 is the line break)

Ctrl+Z -1

This is not to say that the "character" is -1. Rather, there is nothing to read. So basically an EOF.

Now when you load a file with a redirect, the while loop will never stop because -1 is not zero. Yet getchar() keeps returning -1.

Hope this provides some perspective.

Upvotes: -1

Related Questions