BGSU Logo
BGSU Home BGSU Academics BGSU Admissions The Arts BGSU Athletics Libraries Offices
Department of Computer Science
Computer Science Home Undergraduate Program Graduate Program Computer Science Faculty Academic Advising Mission and Vision
Small font Medium font Larger font Largest font
Left bracket Writing data to files using C++ Right bracket

Note: This material is adapted from chapters 11 and 14 of "C++: How to Program" by Deitel and Deitel.

The commands for writing data to a file are (for the most part) very similar to those used to write data to the screen. However, there are some important distinctions which will be addressed in this document.

In order for your program to write to a file, you must:

  1. include the fstream header file and using std::ostream;
  2. declare a variable of type ofstream
  3. open the file
  4. check for an open file error
  5. use the file
  6. close the file when access is no longer needed (optional, but a good practice)
    #include <iostream>
    using std::cerr;
    using std::endl;
    
    #include <fstream>
    using std::ofstream;
    
    #include <cstdlib> // for exit function
    
    // This program output values from an array to a file named example2.dat
    
    int main()
    {
       ofstream outdata; // outdata is like cin
       int i; // loop index
       int num[5] = {4, 3, 6, 7, 12}; // list of output values
    
      outdata.open("example2.dat"); // opens the file
       if( !outdata ) { // file couldn't be opened
          cerr << "Error: file could not be opened" << endl;
          exit(1);
       }
    
      for (i=0; i<5; ++i)
          outdata << num[i] << endl;
       outdata.close();
    
       return 0;
    }
    

In this example, the variable outdata is declared as type ofstream. It is used in the same way that cout is used for doing output to the screen. Several values my be written to the same output record as follows:
outdata << num1 << " " << num2 << " " << num3 << endl;
Spaces are inserted in this statement to separate the output values.

When opening a file, you should always check for success before continuing. The ! operator for the filename returns true if the file can't be opened. You might want to use the following stream manipulators: hex, dec, setw, setfill. You might also be using the following arguments to setf, unsetf, setiosflags and resetiosflags: ios::uppercase, ios::left, ios::right. Use of stream manipulators requires the iomanip header file and appropriate using declarations.


webmaster@cs.bgsu.edu