Writing Data to Files Using C++

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:

  • include the fstream header file and using std::ostream;
  • declare a variable of type ofstream
  • open the file
  • check for an open file error
  • use the file
  • 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.

Updated: 12/01/2017 10:43PM