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

  1. #include <fstream.h>
  2.  
  3. // Example using an ifstream (Input-only File-based stream)
  4. int main(void)
  5. {
  6.    // Declare an ifstream object called "mystream" and initialize
  7.    // it to read bytes from the file "myfile.dat"
  8.    ifstream mystream("sc:examples/streams/myfile.dat");
  9.  
  10.    // Declare an unopened ifstream object called "mystream2"
  11.    ifstream mystream2;
  12.  
  13.    // Declare a pointer to an ifstream object
  14.    ifstream *stream_p;
  15.  
  16.    int i;
  17.  
  18.    if(!mystream)
  19.    {
  20.       cout << "Error opening \"sc:examples/streams/myfile.dat\"!" << endl;
  21.       return 20;
  22.    }
  23.  
  24.    // Read an integer from the file attached to "mystream"
  25.    mystream >> i;
  26.  
  27.    // Print the integer to the program's standard output
  28.    cout << "The integer in the file \"myfile.dat\" is " << i << endl;
  29.  
  30.    // Initialize the unopened "mystream2" stream to read from
  31.    // the file "myfile2.dat"
  32.    mystream2.open("sc:examples/streams/myfile2.dat");
  33.  
  34.    if(!mystream2)
  35.    {
  36.       cout << "Error opening \"sc:examples/streams/myfile2.dat\"!" << endl;
  37.       return 20;
  38.    }
  39.  
  40.    // Read an integer from "myfile2.dat" and print the result
  41.    mystream2 >> i;
  42.  
  43.    cout << "The integer in the file \"myfile2.dat\" is " << i << endl;
  44.  
  45.    // Allocate a new ifstream using "new" and use it to read from
  46.    // the file "myfile3.dat"
  47.    stream_p = new ifstream("sc:examples/streams/myfile3.dat");
  48.  
  49.    if(!stream_p || !*stream_p)
  50.    {
  51.       cout << "Error opening \"sc:examples/streams/myfile3.dat\"!" << endl;
  52.       return 20;
  53.    }
  54.  
  55.    *stream_p >> i;
  56.    cout << "The integer in the file \"myfile3.dat\" is " << i << endl;
  57.  
  58.    // Free the object just allocated.  This will call the destructor
  59.    // for the stream and therefore close the file.
  60.    delete stream_p;
  61.  
  62.    // Destructors for the other streams will automatically be called.
  63.    return 0;
  64. }