Search code examples
cwindowsgetchar

C input - getchar()


It's a basic question.. but had to ask. For a program like this, if the use case is 123^Z, the program doesnt terminate, even though i put an EOF at the end (Ctrl+Z). Why is that so? It's only when I put an EOF after a CR that it works. Any anwers will be appreciated. Thanks.

#include < stdio.h>

void main()
{
    int i, nc;

    nc = 0;
    i = getchar();
    while (i != EOF) {
        nc = nc + 1;
        i = getchar();
    }
    printf("Number of characters in file = %d\n", nc);
}

Solution

  • In Windows, the Ctrl-Z shortcut will only take effect if it's pressed at the start of a line. Otherwise, the OS ignores it. You must press "enter" or "return" to insert a newline character first.

    In Unix, the Ctrl-D shortcut will flush stdin immediately (as mentioned in the below comments), but will not cause getchar() to return EOF unless you are on a new, blank line; same as in Windows.

    From the comments (below):

    There is no "EOF character" on Unix. An EOF is simply a zero-length read. It happens at the end of ordinary files, and can be forced on a terminal by pressing the control character that's been setup in the terminal settings for EOF (usually ^D). The reason ^D "doesn't work" when the terminal buffer is non-empty is that it doesn't actually insert something in the stream; it just causes the pending read to return, but since the input length is nonzero, it's not treated as an "EOF" by the application.

    This addresses a good point - no file actually contains EOF - and pressing Ctrl-D won't "insert" (as I had previously said) anything into the stdin stream. It just flushes stdin. EOF is a standard macro representing a notification that the end of the file was reached by a standard function.

    Thanks to @R. for the explanation about EOF.