Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c

unix

eof

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);
}
like image 914
Sam Avatar asked Aug 14 '12 00:08

Sam


People also ask

Why is CTRL-D EOF?

the “end-of-file” (EOF) key combination can be used to quickly log out of any terminal. CTRL-D is also used in programs such as “at” to signal that you have finished typing your commands (the EOF command). key combination is used to stop a process. It can be used to put something in the background temporarily.

How do I disable Getchar?

It should exit if you kill it with CTRL+C, or end the input with CTRL+Z.

Can Getchar return EOF?

If the stream is at end-of-file, the end-of-file indicator is set, and getchar() returns EOF. If a read error occurs, errno is set, and getchar() returns EOF.

Why do I have to press CTRL-D twice?

On Unix-like systems (at least by default), an end-of-file condition is triggered by typing Ctrl-D at the beginning of a line or by typing Ctrl-D twice if you're not at the beginning of a line. In the latter case, the last line you read will not have a '\n' at the end of it; you may need to allow for that.


2 Answers

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.

like image 176
Jon Lin Avatar answered Oct 27 '22 12:10

Jon Lin


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 variable d, you need to change your while statement to:

    while((d=getchar())!=EOF) {

This is because the inequality operator has higher precedence than assignment. So, in your code, d would always be either 0 or 1.

like image 33
jxh Avatar answered Oct 27 '22 12:10

jxh