Programming in C

(Barry) #1

362 Chapter 16 Input and Output Operations in C


Program 16.2 Copying Characters from Standard Input to Standard Output
// Program to echo characters until an end of file

#include <stdio.h>

int main (void)
{
int c;

while ( (c = getchar ()) != EOF )
putchar (c);

return 0;
}

If you compile and execute Program 16.2, redirecting the input to a file with a com-
mand such as
copyprog < infile
the program displays the contents of the file infileat the terminal.Try it and see!
Actually, the program serves the same basic function as the catcommand under Unix,
and you can use it to display the contents of any text file you choose.
In thewhileloop of Program 16.2, the character that is returned by the getchar
function is assigned to the variable cand is then compared against the defined value EOF.
If the values are equal, this means that you have read the final character from the file.
One important point must be mentioned with respect to the EOFvalue that is returned
by the getcharfunction:The function actually returns an intand not a char.This is
because the EOFvalue must be unique; that is, it cannot be equal to the value of any
character that would normally be returned by getchar.Therefore, the value returned by
getcharis assigned to an intand not a charvariable in the preceding program.This
works out okay because C allows you to store characters inside ints, even though, in
general, it might not be the best of programming practices.
If you store the result of the getcharfunction inside a charvariable, the results are
unpredictable. On systems that do sign extension of characters, the code might still work
okay. On systems that don’t do sign extension, you might end up in an infinite loop.
The bottom line is to always remember to store the result of getcharinside an int
so that you can properly detect an end-of-file condition.
The fact that you can make an assignment inside the conditional expression of the
whileloop illustrates the flexibility that C provides in the formation of expressions.The
parentheses are required around the assignment because the assignment operator has
lower precedence than the not equals operator.
Free download pdf