The simplest way to read from or write to a file is to write your code
with cin
and cout
and use redirection.
Suppose you wanted to do both at the same time. If your program is
called myprog
and you would like to take input from infile
and write output to outfile
, you would run
it like this:
myprog < infile > outfileBut this design works only if you have only one standard input or output stream. Suppose you write a program that needs values from a table in a file called
tabledata
and also requires prompting the
user for some parameters. Logically there are then two input streams.
The solution is to use the class ifstream
, which is
derived from the class istream
, so has many of its
methods. The extra f
reminds us that it deals with a
file instead of standard input. The class ofstream
is
used for output to a file. Both of these classes are defined in the
standard C++ library header fstream
.
Here are the steps required for handling a file for either input or output:
ifstream
or ofstream
.
|
table
can be whatever we
want. We could create a new instance of the class for each file we
wanted to read. Notice that we use it with >>
just like
cin
. The class method open
takes the name
of the file as its character string argument. That argument can also
be a character array containing the name of the file to be opened.
The class method close
closes the file. While closing
the file is not absolutely required, it is a good habit, since there
is a (usually generous) upper limit to the number of files that can be
kept open at once. As can be guessed from the example, the method
fail
checks whether the open operation succeeded. It
could fail if the file wasn't there, for example.
It is possible to combine steps 1 and 2 using the constructor that takes a character string with the file name:
ifstream table("tabledata");
The methods eof
and fail
work for the ifstream
class.