Programming in C

(Barry) #1
Input and Output Operations with Files 361

terminal.The scanffunction itself does not actually know (or care) whether its input is
coming from your window or from a file; all it cares about is that it is properly formatted.
Naturally, you can redirect the input and the output to a program at the same time.
The command


reverse < number > data


causes execution of the program contained in reverseto read all program input from
the file numberand to write all program results into the file data.So, if you execute the
previous command for Program 5.8, the input is once again taken from the file number,
and the output is written into the file data.
The method of redirecting the program’s input and/or its output is often practical.
For example, suppose you are writing an article for a magazine and have typed the text
into a file called article.Program 10.8 counted the number of words that appeared in
lines of text entered at the terminal.You could use this very same program to count the
number of words in your article simply by typing in the following command:^2


wordcount < article


Of course, you have to remember to include an extra carriage return at the end of the
articlefile because your program was designed to recognize an end-of-data condition
by the presence of a single newline character on a line.
Note that I/O redirection, as described here, is not actually part of the ANSI defini-
tion of C.This means that you might find operating systems that don’t support it.
Luckily, most do.


End of File


The preceding point about end of data is worthy of more discussion.When dealing with
files, this condition is called end of file. An end-of-file condition exists when the final
piece of data has been read from a file. Attempting to read past the end of the file might
cause the program to terminate with an error, or it might cause the program to go into
an infinite loop if this condition is not checked by the program. Luckily, most of the
functions from the standard I/O library return a special flag to indicate when a program
has reached the end of a file.The value of this flag is equal to a special name called EOF,
which is defined in the standard I/O include file <stdio.h>.
As an example of the use of the EOFtest in combination with the getcharfunction,
Program 16.2 reads in characters and echoes them back in the terminal window until an
end of file is reached. Notice the expression contained inside the whileloop. As you can
see, an assignment does not have to be made in a separate statement.



  1. Unix systems provide a wccommand, which can also count words. Also, recall that this program
    was designed to work on text files, not word processing files, such as MS Word .doc files.

Free download pdf