Why do i have to input EOF 3 times when using fgets?

前端 未结 1 1867
既然无缘
既然无缘 2021-01-07 01:18

So basically I want to copy everything i write to stdin (including newline char) to string for hash purposes. I managed to accomplish that and made small code to represent m

相关标签:
1条回答
  • 2021-01-07 01:56

    First of all, ^Z or ^D are control characters that mean something to the terminal you are using, and sometimes that means for the terminal to signal end-of-file condition.

    Anyway, your three keypresses are processed by the terminal to take the following actions, after entering text:

    1. Flush the input (i.e. send the characters that have been input so far from the terminal to the program - by default this doesn't happen as the terminal uses line buffering)
    2. Set end-of-file condition
    3. Set end-of-file condition again

    Inside your program that corresponds to:

    1. Nothing happens: even though a is received, fgets keeps reading until end-of-file or newline
    2. fgets completes because of end-of file. However it does not return NULL because characters were read, "a" to be specific.
    3. fgets completes because of end-of-file, and returns NULL because there were no characters read.
    0 讨论(0)
提交回复
热议问题