File Input and Output

If you want to prepare input data ahead, you may store the data in a file and direct the program to read its input from a file. If you want to save output data in a file to use later, you may direct the program to write to a file. To read and/or write to a file, do the following:
  1. Request the preprocessor to include file fstream as well as iostream. fstream contains the declarations for defining input and output streams with files other than cin and cout.
  2. Declare an input stream to be of type ifstream or an output stream to be of type ofstream.
  3. Prepare the stream for use by using the function named open provided in file fstream. The parameter for the function open is the external name of the file. The external name is the name under which the file is stored on the disk.
  4. Put the internal file name to the left of the insertion or extraction operator.

Here is an example program that reads four floating point data values from a file and writes to another file in the reverse order.


// Program IODemo demonstrates how to use files

#include <iostream>
#include <fstream>
using namespace std;

int main()
{
    cout  << fixed  << showpoint;
    //sets all printout in decimal format with decimal points appearing

    float val1, val2, val3, val4;	// declares 4 variables
    ifstream inData;			// declares input stream
    ofstream outData;			// declares output stream

    inData.open("inputfile.dat");
    // binds program variable inData to the input file "inputfile.dat"

    outData.open("outputfile.dat");
     // binds program variable outData to the output file "outputfile.dat"

    inData  >> val1 >> val2 >> val3 >> val4;	// inputs 4 values
    outData  << val4  << endl;
    outData  << val3  << endl;
    outData  << val2  << endl;
    outData  << val1  << endl;	// outputs 4 values
    return 0;
}

Each file in your program has both an internal name and an external name. The internal name is what you call it in your program; the external name is the name the operating system knows it by. Somehow, these two names must be associated with one another. This association is called binding and is done in function open. Notice that inData and outData are identifiers in the program; "inputfile.dat" and "outputfile.dat" are character strings. inputfile.dat is the name that was used when the input data file was created; outputfile.dat is the name of the file where the answers are stored.

You will need to use the pico or vi text editor to create the input data file according the requirement of the data type and format in your program. The input data file must exist and contain correct data. Otherwise, the input will fail.

For example, in the preceding IODemo program, the input file should look like this:

5.5
6.6
7.7
8.8
You may run the program and experience how File I/O works.


Copyright: Department of Computer Science, University of Regina.