home *** CD-ROM | disk | FTP | other *** search
/ Amiga ISO Collection / AmigaUtilCD2.iso / Programming / C / SASC6571.LZX / examples / streams / ofstream.cpp < prev    next >
Encoding:
C/C++ Source or Header  |  1996-12-24  |  1.6 KB  |  60 lines

  1. #include <fstream.h>
  2.  
  3. // Example using an ofstream (Output-only File-based stream)
  4. int main(void)
  5. {
  6.    // Declare an ofstream object called "mystream" and initialize
  7.    // it to write bytes to the file "myofile.dat"
  8.    ofstream mystream("myofile.dat");
  9.  
  10.    // Declare an unopened ofstream object called "mystream2"
  11.    ofstream mystream2;
  12.  
  13.    // Declare a pointer to an ofstream object
  14.    ofstream *stream_p;
  15.  
  16.    if(!mystream)
  17.    {
  18.       cout << "Error opening file \"myofile.dat\"!" << endl;
  19.       return 20;
  20.    }
  21.  
  22.    // Write an integer to the file attached to "mystream"
  23.    cout << "writing \"123\" to file \"myofile.dat\"" << endl;
  24.    mystream << 123;
  25.  
  26.    // Initialize the unopened "mystream2" stream to write to
  27.    // the file "myofile2.dat"
  28.    mystream2.open("myofile2.dat");
  29.  
  30.    if(!mystream2)
  31.    {
  32.       cout << "Error opening file \"myofile2.dat\"!" << endl;
  33.       return 20;
  34.    }
  35.  
  36.    // Write an integer to "myofile2.dat"
  37.    cout << "writing \"456\" to file \"myofile2.dat\"" << endl;
  38.    mystream2 << 456;
  39.  
  40.    // Allocate a new ofstream using "new" and use it to write to
  41.    // the file "myofile3.dat"
  42.    stream_p = new ofstream("myofile3.dat");
  43.  
  44.    if(!stream_p || !*stream_p)
  45.    {
  46.       cout << "Error opening file \"myofile3.dat\"!" << endl;
  47.       return 20;
  48.    }
  49.    cout << "Writing \"789\" to file \"myofile3.dat\"" << endl;
  50.    *stream_p << 789;
  51.  
  52.    // Free the object just allocated.  This will call the destructor
  53.    // for the stream and therefore close the file.
  54.    delete stream_p;
  55.  
  56.    // Destructors for the other streams will automatically be called.
  57.    return 0;
  58. }
  59.  
  60.