The simplest input mechanism is to read one character at a time from the standard input (usually the keyboard) with getchar (we have already used this multiple times over this course).
int getchar(void)
getchar returns the next input character each time it is called, or EOF when it encounters end of file. The symbolic constant EOF is defined in stdio.h, as are the input/output library functions. As mentioned before, when you press ^d (ctrl + d) with an empty buffer, getchar() will return with zero bytes, and this gets interpreted as EOF.
In many environments, a file may be substituted for the keyboard by using the < convention for input redirection. For example, if you program example.c uses getchar, then
cc example.c ./a.out < input_file
leads to input characters being read from input_file instead. The program itself is oblivious to this switching of the input; input_file is not included in the command-line argument.
We could feed the output of one program into the input of another program using pipe mechanism (|). Both the programs will be unaware of this. For example:
cc example1.c -o example1 cc example2.c -o example2 example1 | example2
Here, the output of example1.c is fed as input to example2.c.
The function putchar puts a character on to the standard output (screen by default).
int putchar(int)
putchar returns the character written, or EOF if an error occurs. We can redirect the output using >, as shown below:
./a.out > output_file
Let’s look at the following program that converts input to uppercase.
#include <stdio.h> #include <ctype.h> int main() { int c; while ((c = getchar()) != EOF) /* ^d to terminate the loop */ putchar(toupper(c)); return 0; }
toupper() is defined in ctype.h header file.