3
#include <stdio.h>

// copy input to output
// my version

int main()
{
    int c;

    printf("\n\nUse CONTROL + D to terminate this program\n\n");

    while ((c = getchar()) != EOF) {
        putchar(c);
    }

    if ((c = getchar()) == EOF) {
        printf("\n\nProgram TERMINATED\n\n");
    }

    return 0;
}

When I enter control + D, the body of the if statement runs. That's what I had wanted, but as I analyzed the code more thoroughly, shouldn't it ask for my input again since the if's condition is (c = getchar()) == EOF?

Espresso
  • 4,722
  • 1
  • 24
  • 33

3 Answers3

2

When you hit ^D, input to the program is closed, so getchar() will subsequently always return EOF.

  • Then how do I get input again if every call to `getchar()` wouldn't work after `^D`? – Espresso Jul 15 '11 at 01:58
  • Use something other than `^D` (and the subsequent end-of-file) to terminate your input. –  Jul 15 '11 at 05:23
1

Control-D is canonical mode end-of-file character. When entered at the beginning of a line it causes an EOF condition to be seen by the process, that is the read returns 0. However if if Control-D is entered somewhere other than the beginning of the line it just causes the read to return immediately with what has been input thus far.

If you hit Control-D twice in a row you should see what I think you asking about.

EDIT

Here is a pretty good explanation.

Community
  • 1
  • 1
Duck
  • 26,924
  • 5
  • 64
  • 92
0

^D terminates the program instantly. Thus you're getchar would never return when ^D is hit.

That is why REPL like python exits using 'exit()'.

If you want, try to use 'q' for quiting:

  • 4
    This could be phrased better - `^D` doesn't in general terminate programs, just their input. The program could feel free to ignore the lack of input and go on its merry way. – Cascabel Jul 15 '11 at 01:32