// ofstreamDemo.cc  P. Conrad, 4/8/2004 for CISC181
// demonstrate writing to a file (an "ofstream" object)
// updated 02/05/2007

#include <iostream>

#include <fstream> // for ofstream

using std::ofstream;
using std::cout;
using std::cin;
using std::ios;
using std::cerr;
using std::endl;

int main ()
{


  int x=3;        // x and y are variables just for demonstration purposes 
  double y=4.5;
  
  // open the output file
  // the ofstream and ios::out parts need to be retained exactly
  // the name "output.txt" is any filename of our choosing; the file
  //   will be known by that name in our directory.
  // the name outfile is a variable that we will use to refer to the
  //   output file in our C++ code; we'll use statements like 
  //   outfile >> x;  instead of cout >> x; 

  ofstream outfile("output.txt",ios::out); 

  // always check the status of the file after you try to open it.
  // there are several reasons why an open might fail 
  // (e.g. over disk quota, illegal file name, etc...)

  if (!outfile) // overloaded ! operator to check status of file
    {
      cerr << "File output.txt could not be opened: " << endl;
      exit(1);
    }
  
  /* write some output to the file */
  
  outfile << "This output is going to the file output.txt." << endl;
  
  cout << "This output is going to the terminal." << endl;
  cout << "I can still write to the terminal in the same program" << endl;
  cout << "that I am writing to a file." << endl;
  
  outfile << "I can also print the value of variables to a file." << endl;
  outfile << "for example, x=" << x << ", y=" << y << endl;
  outfile << "Bye now!" << endl;
  
  // close the output file this is done automatically at the end of
  // your program even if you don't include this line of code, but it
  // is better style to explicitly call outfile.close().  In a large
  // program it may be necessary to open many files, and there is a
  // limit on how many files can be open at one time.
  
  outfile.close(); 
  
  return 0;
}


