What is EOF in the C programming language?

Chris_45 picture Chris_45 · Nov 23, 2009 · Viewed 172.3k times · Source

How do you get to see the last print? In other words what to put in for EOF? I checked the definitions and it says EOF is -1.

And if you enter Ctrl-D you won't see anything.

#include <stdio.h>

int main() {
 int c;
 while((c = getchar() != EOF)) {
  printf("%d\n", c);
 }
 printf("%d - at EOF\n", c);
}

Answer

Carl Smotricz picture Carl Smotricz · Nov 23, 2009

On Linux systems and OS X, the character to input to cause an EOF is Ctrl-D. For Windows, it's Ctrl-Z.

Depending on the operating system, this character will only work if it's the first character on a line, i.e. the first character after an Enter. Since console input is often line-oriented, the system may also not recognize the EOF character until after you've followed it up with an Enter.

And yes, if that character is recognized as an EOF, then your program will never see the actual character. Instead, a C program will get a -1 from getchar().