This week is an extension of Week 6, in which we use the methods of Chapters 6, 7 and now Chapter 8. Inheritance is introduced here in that the data files inherit the iostream insertion (<<) and extraction (>>) operators, as well as all the other data formatting operations of iomanip. We also introduce examples of separating program files into header (.h) files and program (.cpp) files.
In Chapter 8 the following file related items are introduced:
#include <fstream> - basic file stream input/output.
#include <cassert> - if we wish to "assert" that a file opened successfullyifstream infile("raw.data");
This declares a file stream variable named infile and associates this symbolic name with an actual disk file named "raw.data" which is opened for input.ofstream outfile("process.data");
This declares a file stream variable named outfile and associates it with a new disk file named "process.data" which is opened for output.After an attempt is made to open a file with the above statements, we should always check to see if the operation was successful. This can be done with the function fail(), typically as follows:
if(infile.fail()) cout << "ERROR: Cannot open \"raw.data\"\n"; else { cout << "\"raw.data\" file opened\n"; ... }Alternatively we can use the assert function to test if an input or output file opened successfully. We usually use this function for output data files:
assert(outfile);
Note that failing an assertion causes the program to abort with a "core" dump, nevertheless it is ok to use it, and you will get full grade in spite of Dr. Iz's comments and the fact that the assert function is not even mentioned in Friedman and Koffman.As an example of file usage, if we have a sequence of integer numbers in infile which we would like to transfer to outfile:
int num; while(infile >> num) outfile << num << endl;Another very popular usage is that of reading a sequence of characters from a file and displaying them on the standard output as follows:
char ch; while(infile.get(ch)) cout << ch;Note that after using a file it should always be closed:
infile.close();
outfile.close();
The various examples following have been loaded onto "condor" and are relevant to this chapter. After logging in, change directory to the week7 directory and list the various files as follows:
cd /home/condor/et181/week7
ls
