9 Simple use of files
DEALING WITH MORE DATA
Realistic examples of programs with loops and selection generally have to work
with largish amounts of data. Programs need different data inputs to test the code
for all their different selections. It is tiresome to have to type in large amounts of
data every time a program is tested. Also, if data always have to be keyed in, input
errors become more likely. Rather than have the majority of the data entered each
time the program is run, the input data can be keyed into a text file once. Then,
each time the program is subsequently run on the same data, the input can be taken
from this file.
While some aspects of file use have to be left to later, it is worth introducing
simple ways of using files. Many of the later example programs will be organized
as shown in Figure 9.1.
to a file
cout to computer
cin for keyed
Programs using file i/o to supplement standard input and output.
These programs will typically send most of their output to the screen, though
some may also send results to output files on disks. Inputs will be taken from file
Simple use of files
or, in some cases, from both file and keyboard. (Input files can be created with the
editor part of the integrated development environment used for programming, or
can be created using any word processor that permits files to be saved as "text
Input files (and any output files) will be simply text files. Their names should
be chosen so that it obvious that they contain data and are not "header" (".h") or
"code" (".cp") files. Some environments may specify naming conventions for such
data files. If there are no prescribed naming schemes, then adopt a scheme where
data files have names that end with ".dat" or ".txt".
Data files based on text are easy to work with; you can always read them and
change them with word processors etc. Much later, you will work with files that
hold data in the internal binary form used in programs. S