Section 3 - Output Streams

9B.3.1 Opening Output File Streams

Opening a file for output is equally easy:

ofstream outfile("myOutputFile.txt");

As before, this is an instantiation of an ofstream object which we are naming outfile.  Also, we are passing the string "myOutputFile.txt" to the constructor of this object.  This results in the variable outfile being associated with the file "myOutputFile.txt" for the duration of this method.

What could go wrong?  This:

This should not be the case for you in our example.  Still, we test to see if the ofstream was successfully opened, and to do that we test ofstream for null or non-null:

if (!outfile)
{
  cout << "couldn't open myOutputFile for output.\n";
  exit(2);
}

The 1 and 2 in the exit statements are for use by the operating system client.  They will probably be ignored, but if someone writes a script to run your program, he or she can test the exit codes to see what went wrong.

9B.3.2 Writing Data To File Streams

This is even easier than reading.  Just treat the file stream as you would cout:

// now write to output file
outfile << name << " believes that " <<  x << " plus "
<< y << " equals " << x+y << endl;

And that sums it all up!

Here is the entire listing of our sample:

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

// --------------- main ---------------
int main()
{
  int x, y;
  string name;
  string line;

  // open two files for reading and writing
  ifstream infile("myInputFile.txt");
  ofstream outfile("myOutputFile.txt");

  if (!infile)
  {
    cout << "couldn't open myInputFile.txt for input.\n";
    exit(1);
  }

  if (!outfile)
  {
    cout << "couldn't open myOutputFile for output.\n";
    exit(2);
  }

  // read 1st line from file and store into string name
  getline(infile, line);
  name = line;
  cout << "Name: " << name << endl;

  // read 2nd line from file treating first 2 words as numbers
  getline(infile, line);
  istringstream(line) >> x >> y;
  cout << "x: " << x << " y: " << y << endl;

  // now write to output file
  outfile << name << " believes that " <<  x << " plus "
  << y << " equals " << x+y << endl;

  return 0;
}

When done, the console will show this:

console shot

And the file myOutputFile.txt will contain this:

console shot

You can check the contents of myOutputFile.txt by reading it into any application, but you may as well read it into your IDE as I did .