2
/* getchar.c */

#include <stdio.h>

int main(void)
{
    int c;
    while ((c = getchar()) != EOF) {
        putchar(c);
        putchar(c);
    }
    return 0;
}

This is an example code of getchar() and putchar() in 'a book on C'. Then I heard simply from my professor that how getchar() works.

  1. standatd input is stored in buffer.
  2. getchar() read a character from buffer at once.
  3. if there is no more character, then buffer return -1.
  4. There is < called 'redirection' which can be substitution(poor english...) of standard input.

$ gcc getchar.c -o getchar

echo "abc" > input

It worked when I use < redirection as an input.
$ ./getchar < input,
But when I just typed, it didn't terminated.
$ ./getchar
abc


Then I thought that maybe I misunderstood and this process will be correct:

  1. when I use <, a contents input 'file' is stored in buffer with EOF (= -1) like a NULL of string.

  2. So getchar() read -1 when it read all contents of input file in buffer, and loop terminates.

  3. when I just typed(standard input), then what I typed is stored in buffer with '\n' (End Of Line).

  4. So getchar() read \n when it read all contents of standard input in buffer, and loop doesn't terminate.

Is it correct? or is there anything that I don't know? (e.g. buffer really returns -1 but conditionally, ...)

  • 2
    When you don't use redirection, there's no automatic `EOF` that the program is looking for. On POSIX systems like Linux and macOS you must press the `Ctrl-D` key combination. On Windows it's `Ctrl-Z` (on a new line). When you use input redirection the `EOF` is sent to your program when the actual file ends. – Some programmer dude Dec 17 '22 at 13:47
  • https://latedev.wordpress.com/2012/12/04/all-about-eof/ is a good read. – Shawn Dec 17 '22 at 14:50

0 Answers0