Stream Input/Output in C++ - dummies

By Stephen R. Davis

The C++ classes ifstream and ofstream are subclasses of istream and ostream designed to perform stream input and output to disk files. You can use the same extractors and inserters on ifstream and ofstream objects that you’ve been using on cin and cout.

The ifstream is actually an instantiation of the template class basic_ifstream<T> with T set to char. The basic_ifstream<T> template class is instantiated with other types as well to provide different types of input classes. For example, the wide stream file class wifstream is based on the same basic_ifstream<T> with T set to wchar_t. The ofstream is the same as basic_ofstream<char>.

The classes ifstream and ofstream provide constructors used to open a file for input and output, respectively:

ifstream::ifstream(const char *pszFileName,
 ios_base::openmode mode = ios_base::in);
ofstream::ofstream(const char *pszFileName,
 ios_base::openmode mode = ios_base::out|ios_base::trunc);

The first argument is a pointer to the name of the file to open. The second argument specifies the mode. The type openmode is an integer type defined in ios_base. Also defined within ios_base are the possible values for mode listed in this table.

These are bit fields that the programmer bitwise ORs together. The default mode for ifstream is to open the file for input with the pointer set to the beginning of the file (that’s logical enough).

Constants that Control How Files Are Opened
Flag Meaning
ios_base::app Seek to end-of-file before each write.
ios_base::ate Seek to end-of-file immediately after opening the file, if it
exists.
ios_base::binary Open file in binary mode (alternative is text mode).
ios_base::in Open file for input (implied for istream).
ios_base::out Open file for output (implied for ostream).
ios_base::trunc Truncate file, if it exists (default for ostream).

The default for ofstream is to open for output and to truncate the file if it exists already. The alternative to truncate is ios_base::app, which means append new output onto the end of the file if it exists already. Both options create a file if it doesn’t already exist.

For example, the following StreamOutput program opens the file MyName.txt and then writes some important and absolutely true information to that file:

// StreamOutput - simple output to a file
#include <fstream>
using namespace std;
int main(int nNumberofArgs, char* pszArgs[])
{
    ofstream my("MyName.txt");
    my << "Stephen Davis is suave and handsomen"
       << "and definitely not balding prematurely"
       << endl;
    return 0;
}

The destructor for the file stream classes automatically close the associated file. In this simple example, the MyName.txt file was closed when the my object went out of scope upon returning from main(). Global objects are closed as part of program termination.