getchar() and conditioning a loop to break with a specific char

我的梦境 提交于 2019-12-23 04:49:07

问题


I am working on the infamous book "Prentice Hall Software Series" and trying out the Code they write and modifying it to learn more about C.

I am working with VIM on Fedora 25 in the console. The following code is a quote from the book, I know "int" is missing as well as argc and argv etc.

Kernighan and Ritchie - The C Programming Language: Page 20

#include <stdio.h>
/* copy input to output; 1st version  */   
main(){       
    int c;
    c = getchar();       
    while (c != EOF) {           
        putchar(c);           
        c = getchar();       
    }   
}

With this code I couldn't manage to get the "EOF" to work. I am not sure if "ctr + z" really is the real thing to do, since it quits any console program in console.

Well since I was unsure i changed the condition to

...
while (c != 'a') {
...

So normally if I enter 'a' the while condition should break and the programm should terminate. Well it does not when I try to run it and enter 'a'. What is the problem here?

Thank you guys!


回答1:


There's nothing wrong with the code (except the archaic declaration of main).

Usually, on Unixes end of file is signalled to the program by ctrl-D. If you hit ctrl-D either straight away or after hitting new-line, your program will read EOF.

However, the above short explanation hides a lot of subtleties.

In Unix, terminal input can operate in one of two modes (called IIRC raw and cooked). In cooked mode - the default - the OS will buffer input from the terminal until it either reads a new line or a ctrl-D character. It then sends the buffered input to your program.

Ultimately, your program will use the read system call to read the input. read will return the number of characters read but normally will block until it has some characters to read. getchar then passes them one by one to its caller. So getchar will block until a whole line of text has been received before it processes any of the characters in that line. (This is why it still didn't work when you used a).

By convention, the read system call returns 0 when it gets end of file. This is how getchar knows to return EOF to the caller. ctrl-D has the effect of forcing read to read and empty buffer (if it is sent immediately after a new line) which makes it look to getchar like it's reached EOF even though nobody has closed the input stream. This is why ctrl-D works if it is pressed straight after new line but not if it is pressed after entering some characters.



来源:https://stackoverflow.com/questions/42782905/getchar-and-conditioning-a-loop-to-break-with-a-specific-char

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!