ctrl-d didn't stop the while(getchar()!=EOF) loop

Sam picture Sam · Aug 14, 2012 · Viewed 19.1k times · Source

Here is my code. I run it in ubuntu with terminal. when I type (a CtrlD) in terminal, the program didn't stop but continued to wait for my input.

Isn't CtrlD equal to EOF in unix?

Thank you.

#include<stdio.h>

main() {
    int d;
    while(d=getchar()!=EOF) {
        printf("\"getchar()!=EOF\" result is %d\n", d);
        printf("EOF:%d\n", EOF);
    }
        printf("\"getchar()!=EOF\" result is %d\n", d);
}

Answer

Jon Lin picture Jon Lin · Aug 14, 2012

EOF is not a character. The EOF is a macro that getchar() returns when it reaches the end of input or encounters some kind of error. The ^D is not "an EOF character". What's happening under linux when you hit ^D on a line by itself is that it closes the stream, and the getchar() call reaches the end of input and returns the EOF macro. If you type ^D somewhere in the middle of a line, the stream isn't closed, so getchar() returns values that it read and your loop doesn't exit.

See the stdio section of the C faq for a better description.

Additionally:

On modern systems, it does not reflect any actual end-of-file character stored in a file; it is a signal that no more characters are available.