< previous page page_148 next page >

Page 148
ables in your program. But some computer systems do not use this format for file names on disk. For example, many systems include a dot in file names.) Similarly, the second function call associates the stream variable outMPG with the disk file outmpg.dat. Associating a program's name for a file (outMPG) with the actual name for the file (outmpg.dat) is much the same as associating a program's name for the standard output device (cout) with the actual device (the screen).
The next thing the open function does depends on whether the file is an input file or an output file. With an input file, the open function sets the file reading marker to the first piece of data in the file. (Each input file has its own reading marker.)
With an output file, the open function checks to see whether the file already exists. If the file doesn't exist, open creates a new, empty file for you. If the file does exist, open erases the old contents of the file. Then the writing marker is set at the beginning of the empty file (see Figure 4-3). As output proceeds, each successive output operation advances the writing marker to add data to the end of the file.
Because the reason for opening files is to prepare the files for reading or writing, you must open the files before using any input or output statements that refer to the files. Ina program, it's a good idea to open files right away to be sure that the files are prepared before the program attempts any file I/O.
  .
  .
  .

int main()
{
     .
     .
     .}Declarations
     
  // Open the files

  inMPG.open("inmpg.dat");
  outMPG.open("outmpg.dat");

     .
     .
     .

}
Specifying Files in Input/Output Statements
There is just one more thing we have to do in order to use files. As we said earlier, all istream operations are also valid for the ifstream type, and all ostream operations are valid for the ofstream type. So, to read from or write to a file, all we need to do in our input and output statements is substitute the appropriate file stream variable for cin or cout. In our Mileage program, we would use a statement like

 
< previous page page_148 next page >