48

I have a C program.

int main ()
{
    if (getchar()!=EOF)
        puts("Got a character");
    else
        puts("EOF");
}

What should I type into the stdin on the terminal to produce an EOF?

user1593308
  • 491
  • 1
  • 4
  • 5

4 Answers4

82

In Windows, Control+Z is the typical keyboard shortcut to mean "end of file", in Linux and Unix it's typically Control+D.

unwind
  • 391,730
  • 64
  • 469
  • 606
  • 1
    Sir I want to print the integer value of EOF in C, how can I do this ? – user1593308 Aug 15 '12 at 11:49
  • the integer value of EOF in C is a value<0, so set your variable equal to getchar() and then print it out upon reading EOF –  Oct 16 '13 at 01:08
  • Unhelpfully, this is the first Google hit for "end of file keyboard shortcut". – Toby Wilson Mar 31 '20 at 13:02
  • 1
    @user1593308 Just do `printf("EOF=%d\n", EOF);`, no need to get the value from `getchar()`, just use the macro directly. – unwind Mar 31 '20 at 13:31
17
  1. EOF is wrapped in a macro for a reason - you never need to know the value.
  2. From the command-line, when you are running your program you can send EOF to the program with Ctrl-D (Unix) or CTRL-Z (Microsoft).
  3. To determine what the value of EOF is on your platform you can always just print it:

    printf ("%i\n", EOF);
    
Lelanthran
  • 1,510
  • 12
  • 18
  • 4
    `printf("%i", EOF)` prints `-1` instead of `Control+D` – KMC Apr 05 '13 at 09:54
  • 5
    @KMC - allow me to clarify. Doing this: printf ("%i\n", 'K'); would print '75' and not 'K' after all. I also doubt if printing EOF as a character with "%c" will result in "CTRL+D" being printed. Depending on the terminal you might even get "?". Bear in mind that EOF is what the library returns when you *read* input, and is not representable as a printable character anyway. When you are *writing* output in your terminal, pressing CTRL+D (or whatever) causes the terminal to end input; it does not cause the terminal to generate a specific representation of EOF. Hope this clears things up. – Lelanthran Apr 06 '13 at 10:51
7

You can simulate an EOF with:

  • Windows: ctrl+Z
  • Unix: ctrl+D
activedecay
  • 10,129
  • 5
  • 47
  • 71
SpacedMonkey
  • 2,725
  • 1
  • 16
  • 17
4

It's not mentioned in any of the other answers so far, but you may need to press the right key combo (^D or ^Z) 2 or 3 times in order to actually signal EOF; see here for explanation.

M.M
  • 138,810
  • 21
  • 208
  • 365