< previous page page_147 next page >

Page 147
Declaring File Streams
In a program, you declare stream variables the same way that you declare any variableyou specify the data type and then the variable name:
int      someInt;
float    someFloat;
ifstream inFile;
ofstream outFile;
(You don't have to declare the stream variables cin and cout. The header file iostream.h already does this for you.)
For our Mileage program, let's name the input and output file streams inMPG and outMPG. We declare them like this:
ifstream inMPG;        // Holds gallon amounts and mileages
ofstream outMPG;       // Holds miles per gallon output
Note that the ifstream type is for input files only, and the ofstream type is for output files only. With these data types, you cannot read from and write to the same file. If you wanted to do so, you would use a third data type named fstream, the details of which we don't explore in this book.
Opening Files
The third thing we have to do is prepare each file for reading or writing, an act called opening a file. Opening a file causes the computer's operating system to perform certain actions that allow us to proceed with file I/O.
In our example, we want to read from the file stream inMPG and write to the file stream outMPG. We open the relevant files by using these statements:
inMPG.open(inmpg.dat);
outMPG.open (outmpg.dat);
These statements are both function calls (notice the telltale parametersthe mark of a function). In each function call, the parameter is a string enclosed by quotes. The first statement is a call to a function named open, which is associated with the ifstream data type. The second is a call to another function (also named open) associated with the ofstream data type. As we discussed earlier, we use dot notation (as in inMPG.open) to call certain library functions that are tightly associated with data types.
Exactly what does an open function do? First, it associates a stream variable used in your program with a physical file on disk. Our first function call creates a connection between the stream variable inMPG and the actual disk file, inmpg.dat. (Names of file streams must be identifiers; they are vari-

 
< previous page page_147 next page >