Why does getchar() recognize EOF only in the beginning of a line?

后端 未结 4 1408
情深已故
情深已故 2021-01-05 12:14

This example is from the K&R book

#include


main()
{
    long nc;

    nc = 0;
    while(getchar() != EOF)
        ++nc;
    printf(\"%ld         


        
4条回答
  •  花落未央
    2021-01-05 12:41

    Traditional UNIX interpretation of tty EOF character is to make blocking read return after reading whatever is buffered inside a cooked tty line buffer. In the start of a new line, it means read returning 0 (reading zero bytes), and incidentally, 0-sized read is how the end of file condition on ordinary files is detected.

    That's why the first EOF in the middle of a line just forces the beginning of the line to be read, not making C runtime library detect an end of file. Two EOF characters in a row produce 0-sized read, because the second one forces an empty buffer to be read by an application.

    $ cat
    foo[press ^D]foo <=== after ^D, input printed back before EOL, despite cooked mode. No EOF detected
    foo[press ^D]foo[press ^D] <=== after first ^D, input printed back, and on second ^D, cat detects EOF
    
    $ cat
    Some first line <=== input
    Some first line <=== the line is read and printed
    [press ^D] <=== at line start, ^D forces 0-sized read to happen, cat detects EOF
    

    I assume that your C runtime library imitates the semantics described above (there is no special handling of ^Z at the level of kernel32 calls, let alone system calls, on Windows). That's why it would probably detect EOF after ^Z^Z even in the middle of an input line.

提交回复
热议问题