Make your own free website on Tripod.com

                    Lesson 10: C++ File I/O

Prev || Home || Next

bar.gif (11170 bytes)

    This is a slightly more advanced topic than what I have covered so far, but I think that it is useful. File I/O is reading from and writing to files. This lesson will only cover text files, that is, files that are composed only of ASCII text.

    C++ has two basic classes to handle files, ifstream and ofstream. To use them, include the header file fstream.h. Ifstream handles file input (reading from files), and ofstream handles file output (writing to files). The way to declare an instance of the ifstream or ofstream class is:


ifstream a_file;
//or
ifstream a_file("filename");


    The constructor for both classes will actually open the file if you pass the name as an argument. As well, both classes have an open command (a_file.open()) and a close command (a_file.close()). It is generally a good idea to clean up after yourself and close files once you are finished.

    The beauty of the C++ method of handling files rests in the simplicity of the actual functions used in basic input and output operations. Because C++ supports overloading operators, it is possible to use << and >> in front of the instance of the class as if it were cout or cin.

For example:


#include <fstream.h>
#include <iostream.h>

int main()
{
char str[10];
            //Used later
ofstream a_file("example.txt");
            //Creates an instance of ofstream, and opens example.txt
a_file<<"This text will now be inside of example.txt";
            //Outputs to example.txt through a_file
a_file.close();
            //Closes up the file

ifstream b_file("example.txt");
            //Opens for reading the file
b_file>>str;
//Reads one string from the file
cout<<str;
//Should output 'this'
b_file.close();
//Do not forget this!
}


The default mode for opening a file with ofstream's constructor is to create it if it does not exist, or delete everything in it if something does exist in it. If necessary, you can give a second argument that specifies how the file should be handled. They are listed below:

ios::app -- Opens the file, and allows additions at the end
ios::ate -- Opens the file, but allows additions anywhere
ios::trunc -- Deletes everything in the file
ios::nocreate -- Does not open if the file must be created
ios::noreplace -- Does not open if the file already exists

For example:

ifstream a_file("test.txt", ios::nocreate);

The above code will only open the file test.txt if that file does not already exist.

bar.gif (11170 bytes)

Prev || Home || Next