Computer Systems Org I - Prof. Grishman

Lecture 15 - Oct. 25, 2005

IO with putchar and getchar

The C functions getchar and putchar read one character from standard input and write one character to standard output.  So, for example, to copy from input to output until you find a 'q',

#include <stdio.h>

main() {
   char c;
   /* copy input characters to output until we find a 'q' */
   while ((c = getchar()) != 'q') putchar(c);
}

Redirection

getchar reads a character from standard input;  putchar writes a character to standard output.
In Unix (and systems using similar shells, like Linux and Cygwin) standard input can be redirected to read from a file

./a <sometext

reads from file 'sometext' instead of standard input;

./a <sometext >moretext

reads from file 'sometext' and writes to file 'moretext'.  This allows a program to be tested first interactively and then -- without changing the program, to use a data file as input.

EOF

If getchar is reading from a file and encounters an end-of-file, it returns the value EOF, which is defined as part of stdio.h.  So a program to copy a complete file from input to output would be

#include <stdio.h>

main() {
   char c;
   /* copy input characters to output until end of file */
   while ((c = getchar()) != EOF) putchar(c);
}

Note:  because EOF is an integer but not a character, it would be better to declare c an int in this program; however, a char declaration will work on most machines.