CITS2002 Systems Programming  
prev
next CITS2002 CITS2002 schedule  

File streams

File handling in C++ works almost identically to terminal input/output. To use files, we #include <fstream<> and then access two standard classes from the std:: namespace:

  • ifstream : allows reading input from files

  • ofstream : allows outputting to files

Each open file is represented by a separate ifstream or an ofstream object.

You can use ifstream objects in exactly the same way as cin and ofstream objects in the same way as cout, except that you need to declare new objects and specify what files to open.

#include <fstream>

using namespace std;

int main(void)
{
    ifstream source("source-file.txt");
    ofstream destination("dest-file.txt");

    int x;

    source >> x; // Reads one int from source-file.txt
    source.close(); // close file as soon as we're done using it

    destination << x; // Writes x to dest-file.txt

    return 0;
}   // close() called on destination by its destructor

 


CITS2002 Systems Programming, Lecture 23, p13, 17th October 2023.