File I/O

This document defines the syntax necessary to read from, and write to files in a C++ program.

  1. Direct the C++ preprocessor to include fstream and iostream.
    e.g. #include <iostream.h> and #include <fstream.h>

  2. Declare input streams to be of type ifstream.
    e.g. ifstream inData;
    Be aware that inData in this example is simply an identifier name selected by the programmer.

  3. Declare output streams to be of type ofstream.
    e.g. ofstream outData;
    Be aware that outData in this example is simply an identifier name selected by the programmer.

  4. Use the open function to associate file stream identifiers with disk files.
    e.g.1 inData.open("file_input.txt");
    e.g.2 outData.open("file_output.txt");

  5. Check the value of the file identifier to ensure that there was no problem reading or writing to disk.
    e.g.
        if (!inData)
           {
           cout << "** Problem: cannot open file_input.txt, ending program."
    	    << endl;
           return 1;
           }
    
    Note that this step is not mandatory, but it is good programming practice.

  6. When reading or writing to file streams, put the file identifier to the left of the insertion or extraction operator.
    e.g.1 inData >> inVar1 >> inVar2;
    e.g.2 outData << inVar1;

The following C++ program illustrates file I/O with simple error checks after the open statements.


/****************************************************
*
*  FileName:	~ftp/pub/class/cplusplus/Csyntax-files/Cpgms/file_io.cpp
*  Author:	Ada Lovelace
*  Purpose:
*		Demonstrate simple file I/O 
*
********************************************************/

#include <iostream.h>
#include <fstream.h>
#include <string>

using namespace std;

int main() {

    ifstream inData;
    ofstream outData;

    string inVar1;
    string inVar2;


    cout << endl << "This program reads from an input file, file_input.txt,"
	 << endl << " and writes to an output file, file_output.txt" << endl;

    inData.open("file_input.txt");
    if (!inData)
       {
       cout << "** Problem: cannot open file_input.txt, ending program."
	    << endl;
       return 1;
       }

    outData.open("file_output.txt");
    if (!outData)
       {
       cout << "** Problem: cannot open file_output.txt, ending program."
	    << endl;
       return 1;
       }

    inData >> inVar1 >> inVar2;

    while ( inData)
       {
       outData << inVar2;     // output in reverse order
       outData << " ";
       outData << inVar1;     
       outData << endl;     

       inData >> inVar1 >> inVar2;

       } // end while
    
    inData.close();
    outData.close();

} // end main

This page has been accessed     times.
Last modified: Friday, 21-Aug-2020 15:28:13 CST
Copyright 2000 Department of Computer Science, University of Regina.


 CS Dept Home Page

Teaching Material