/* 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.
- standatd input is stored in buffer.
getchar()
read a character from buffer at once.- if there is no more character, then buffer return -1.
- 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:
when I use
<
, a contents input 'file' is stored in buffer withEOF (= -1)
like aNULL
of string.So
getchar()
read-1
when it read all contents of input file in buffer, and loop terminates.when I just typed(standard input), then what I typed is stored in buffer with
'\n' (End Of Line)
.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, ...)