< previous page page_146 next page >

Page 146
0146-01.jpg
Figure 4-2
3.5-inch and 5.25-inch Floppy Disks
Using Files
If we want a program to use file I/O, we have to do four things:
1. Request the preprocessor to include the header file fstream.h.
2. Use declaration statements to declare the files we are going to use.
3. Prepare each file for reading or writing by using a function named open.
4. Specify the name of the file in each input or output statement.
Including the Header File fstream.h
Suppose we want the Mileage program (page 83) to read data from a file and to write its output to a file. The first thing we must do is use the preprocessor directive
#include <fstream.h>
Through the header file fstream.h, the C++ standard library defines two data types, ifstream and ofstream (standing for input file stream and output file stream). Consistent with the general idea of streams in C++, the ifstream data type represents a stream of characters coming from an input file, and ofstream represents a stream of characters going to an output file.
All of the istream operations you have learned aboutthe extraction operator (>>), the get function, and the ignore functionare also valid for the ifstream type. And all of the ostream operations, like the insertion operator (<) and the endl, setw, and setprecision manipulators, apply also to the ofstream type. To these basic operations, the ifstream and ofstream types add some more operations designed specifically for file I/O.

 
< previous page page_146 next page >