Next: Summary
Up: Streams and External Files
Previous: Connecting Streams to External
In the above the functions open
and fail
have been
attached to a stream name. Another function that can be attached to a
stream name is the end-of-file condition, eof
. This condition
is set true when an an attempt is made to read beyond the end of a
file, otherwise it is set to false. Unlike some other languages the
end-of-file character is actually entered and the eof
function
returns true when it is entered. For example to read values from a
file and evaluate their average then the following code could be used:
#include <iostream.h> #include <fstream.h> #include <iomanip.h> int main() { int n; float x, sum, average; ifstream ins; // input stream ofstream outs; // output stream ins.open("indata.dat"); // open files, exit program if fail if (ins.fail()) { cout << "Can't open indata.dat" <<endl; return 1; //exit with code 1 for failure } outs.open("results.dat"); if (outs.fail()) { cout << "Can't open results.dat" << endl; return 1; //exit with code 1 for failure } // Initialise and let user know something is happening sum = 0.0; n = 0; cout << "Reading input file " << endl; // read from file, accumulate sum and output average // to output file. ins >> x; // if file was empty then eof would now be true while (!ins.eof()) { sum += x; n++; ins >> x; } average = sum / n; cout << "Writing results to file " << endl; outs << "The average of " << n << " numbers is " << setprecision(2) << average << endl; ins.close(); // Close all files - GOOD PRACTICE outs.close(); return 0; // indicate success }
Download program.
Download sample data.
Note that at the end the streams ins
and outs
were
closed. While some operating systems will do this automatically when
your program terminates it is good practice to always close files
before exiting a program. If this is not done then sometimes not all
of the output is written to the file.
If the program was to be run again with data from a different file
then the only way this could be done would be to edit the program
above and replace each occurrence of indata.dat
with the name
of the other input file. This is obviously inconvenient and it is
much better to allow the user to enter the file name at run-time.
However this topic is delayed until
Lesson 23 when further consideration has
been given to the representation of arbitrary strings within a program.