I'm reading The C Programming Language and have understood everything so far. However when I came across the getchar()
and putchar()
, I failed to understand what is their use, and more specifically, what the following code does.
main() { int c; while ((c = getchar()) != EOF) putchar(c); }
I understand the main()
function, the declaration of the integer c
and the while
loop. Yet I'm confused about the condition inside of the while
loop. What is the input in this C code, and what is the output.
Sorry if this is a basic and stupid question, but I'm just looking for a simple explanation before I move on in the book and become more confused.
getchar() is a function that reads a character from standard input. EOF is a special character used in C to state that the END OF FILE has been reached.
If the stream is at end-of-file, the end-of-file indicator is set, and getchar() returns EOF. If a read error occurs, errno is set, and getchar() returns EOF.
Verify that getchar() != EOF IS 0 OR 1 c is assigned the next character from the keyboard. c is checked whether it is EOF or not. c is assigned 1 or 0, depending if it is EOF or not. character is shown on output, or if EOF ends the program.
In computing, end-of-file (EOF) is a condition in a computer operating system where no more data can be read from a data source.
This code can be written more clearly as:
main() { int c; while (1) { c = getchar(); // Get one character from the input if (c == EOF) { break; } // Exit the loop if we receive EOF ("end of file") putchar(c); // Put the character to the output } }
The EOF
character is received when there is no more input. The name makes more sense in the case where the input is being read from a real file, rather than user input (which is a special case of a file).
main
function should be written as int main(void)
.]
getchar()
is a function that reads a character from standard input. EOF
is a special character used in C to state that the END OF FILE has been reached.
Usually you will get an EOF
character returning from getchar()
when your standard input is other than console (i.e., a file).
If you run your program in unix like this:
$ cat somefile | ./your_program
Then your getchar()
will return every single character in somefile
and EOF
as soon as somefile
ends.
If you run your program like this:
$ ./your_program
And send a EOF
through the console (by hitting CTRL+D
in Unix or CTRL+Z in Windows), then getchar()
will also returns EOF
and the execution will end.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With