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

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. A bug in old versions of glibc causes fgets to try to read again, even though it previously reached end-of-file. fgets completes because of end-of-file, and returns NULL because there were no characters read.

Leave a Comment