TransWikia.com

Why should I press ENTER before CTRL+D to indicate an EOF to stdin?

Stack Overflow Asked by Name Null on December 11, 2020

The following is my code, where I use fgetc to get input from stdin. (running the program from a UNIX shell)

What I don’t understand is that, when I type some characters from the keyboard, and then I press ctrl + D and then press ENTER, the program does not stop. It seems to me that EOF has already been transmitted to the program, why wouldn’t it stop?

I also found that if I press ENTER, then ctrl + D, the program does stop, but why?

#include "stdio.h"

int main()
{
    char ch;
    int i;
    for (i = 0; i < 200; i++)
    {
        ch = fgetc(stdin);
        if (ch == EOF)
            break;
    }
    return 0;
}

One Answer

Saying that Ctrl-D sends EOF is an educational lie-to-children. What it actually does is make any ongoing read() from the terminal return immediately with the contents of the current line buffer if any.

Synergy happens because the Unix convention is that a read() of zero bytes represents EOF.

This means that if you press Ctrl-D with an empty buffer, the read() will return with zero bytes, and a canonical program will interpret it as end-of-file. This is obviously just an illusion since you're still there to input more on the terminal, and a less canonical program could just keep reading if it wanted to.

If you instead press Ctrl-D after entering some data, then that data is just returned and a canonical program will keep reading to find a linefeed or whatever else it's looking for.

This is why EOF behavior is only triggered in canonical programs when Ctrl-D is pressed either after another Ctrl-D (the first flushes the buffer, the second returns a now-empty buffer) or after an Enter (for the same reason).

Correct answer by that other guy on December 11, 2020

Add your own answers!

Ask a Question

Get help from others!

© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP