This question already has an answer here:
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);
}
In addition to Jon Lin's answer about EOF, I am not sure the code you wrote is what you intended. If you want to see the value returned from
getchar
in the variabled
, you need to change yourwhile
statement to:This is because the inequality operator has higher precedence than assignment. So, in your code,
d
would always be either0
or1
.EOF is not a character. The
EOF
is a macro thatgetchar()
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 thegetchar()
call reaches the end of input and returns theEOF
macro. If you type^D
somewhere in the middle of a line, the stream isn't closed, sogetchar()
returns values that it read and your loop doesn't exit.See the stdio section of the C faq for a better description.
Additionally: