Refresher on File IO in C++

Here is a bit of code to refresh your memory on reading and writing files in C++. You should recognize the data types ifstream and ofstream, as well as the open, fail, and eof methods.

This program should also give you an idea of the expected level and type of comments that you should use in your homework.



/*******************************************************
Demo One - Program to demo reading and writing files.
Steve Dannelly
January 2011

This program reads the file "demo1.in" and writes
the file "demo2.out". Each line of the files
contains simply two strings. The strings are
switched in the output file.
*******************************************************/
#include <iostream>
#include <fstream>
#include <cstdlib>
using namespace std;

/******************************************************/
int main ()
{
   ifstream infile;                // the only input file
   ofstream outfile;               // the only output file
   char string1[20], string2[20];  // strings to read and write

   /***** open input and output files *****/
   infile.open ("demo1.in", ios::in);     // open the input
   if (!infile)                           // if it did not open
     {
      cerr << "Error opening input file";
      exit (1);
     }
   outfile.open ("demo1.out", ios::out);  // open the output
   if (outfile.fail())                    // if it did not open
     {
      cerr << "Error opening output file";
      exit (1);
     }

   /***** loop until end of file *****/
   while (infile >> string1 >> string2)  // read 2 strings
      outfile << string2 << " " << string1 << endl;  // write the 2 strings
}