Programming & Scripting Tutorials

C++: File I/O

In this tutorial we are going to go off on a little bit of a tangent and talk about writing and reading files. There are three main header files that are related to this: fstream (file stream) which is for reading and writing files (we’ll be using this for the most part), ifstream (input file stream) which is for reading files only, and ofstream (output file stream) which is for writing files only. So let’s get right into it!


Writing To Files

Firstly let’s setup our basic program structure (with fstream included for our file operations):

#include <iostream>
#include <fstream>

using namespace std;

int main()
{

    return 0;
}

So the first thing we’re going to want to do, is to create an output file stream object. We have to create one of these objects as we use these to output data to files. We can do these by writing the object-type (ofstream) followed by what we want to call our ofstream object, in this case let’s just call it 'myfile':

#include <iostream>
#include <fstream>

using namespace std;

int main()
{
    ofstream myfile; //Create an output file stream for writing to files

    return 0;
}

So now that we have an object that can open and write to files, let’s go ahead and open a file for it to write to! If a file exists with the name we choose to open, then it will open that file to write to – otherwise it will create a file with the name we specify. In this case, we’re going to specify the file name "writingtothisfile.txt".

To actually do the opening, we put the name of our ofstream object (myfile) and then use the . operator to show that we want to use one of it’s preset methods (a method is simply a function performed on an object). We then type open to tell it we want to use the open method, and pass this the name of our target file as a string constant (defined by double quotes in C++) in brackets as this value is required by open:

#include <iostream>
#include <fstream>

using namespace std;

int main()
{
    ofstream myfile; //Create an output file stream for writing to files
    myfile.open("writingtothisfile.txt"); //Open the file for writing

    return 0;
}

Now we can actually write some data to the file! We can do this by using the name of our ofstream object (myfile) and then using some insertation operators (just as your would with cout) to specify the data we want to write. So in this case – let’s just write a simple line of text and a newline to the file:

#include <iostream>
#include <fstream>

using namespace std;

int main()
{
    ofstream myfile; //Create an output file stream for writing to files
    myfile.open("writingtothisfile.txt"); //Open the file for writing
    myfile << "This should be written to a file :D\n";

    return 0;
}

Finally, we can close the file when we are finished using the close method:

#include <iostream>
#include <fstream>

using namespace std;

int main()
{
    ofstream myfile; //Create an output file stream for writing to files
    myfile.open("writingtothisfile.txt"); //Open the file for writing
    myfile << "This should be written to a file :D\n";
    myfile.close();

    return 0;
}

So if you run this now, it should work – and the specified text will be written to the file "writingtothisfile.txt"

But what if we wanted to only write to the file if it existed? Well it’s pretty simple really. The file is created if it doesn’t exist when we actually start writing the data (with the insertation operators and such) – so what we can do is simply open the file, and then use the the is_open method on our ofstream object to check if the file is open (which will essentially check if the file already exists). So we could do something like the following:

#include <iostream>
#include <fstream>

using namespace std;

int main()
{
    ofstream myfile; //Create an output file stream for writing to files
    myfile.open("writingtothisfile.txt"); //Open the file for writing
    if(myfile.is_open())
{
        myfile << "This should be written to a file :D\n";
}
else
{
    cout << "File could not be found.\n";
}
    myfile.close();

    return 0;
}

If you compile this, it should all work as intended! So now we know how to write to files – let’s learn how to read them.


Reading Files

Reading files is very similar to writing, however there are a few differences. Firstly, let’s go back to our simple program structure (with fstream):

#include <iostream>
#include <fstream>

using namespace std;

int main()
{

    return 0;
}

Now we need to create an ifstream object for reading files (much like creating an ofstream object):

#include <iostream>
#include <fstream>

using namespace std;

int main()
{
    ifstream myfile;

    return 0;
}

Now we want to actually loop round to output each character of the file to the screen (since this is what we want our program to do) – we can do this by creating a simple while loop. We can use the condition !myfile.eof() to do this. The eof method checks if we have reached the end of the file and the exclamation mark in front means not. So while we have not reached the end of the file, the code in the loop should execute:

#include <iostream>
#include <fstream>

using namespace std;

int main()
{
    ifstream myfile;
    while(!myfile.eof())
{
    //Code to output a character of the file
}
    return 0;
}

We should also add our ifstream open and close function calls, since these are the same as writing files:

#include <iostream>
#include <fstream>

using namespace std;

int main()
{
    ifstream myfile;
    myfile.open("writingtothisfile.txt");
    while(!myfile.eof())
{
    //Code to output a character of the file
}
myfile.close();
    return 0;
}

In this instance, we’re just opening the "writingtothisfile.txt" that we wrote to in the previous part of this tutorial.

So now we just need to put the code in to get, and then output a character of the file! To do this, we can simply make a char variable (I’m calling mine ‘ch’) and then call the ifstream object's get method and pass it out char variable to put the next character in the file and put it into 'ch':

#include <iostream>
#include <fstream>

using namespace std;

int main()
{
    ifstream myfile;
    char ch;
    myfile.open("writingtothisfile.txt");
    while(!myfile.eof())
    {
        myfile.get(ch);
        cout << ch;
    }
    myfile.close();
    system("PAUSE");
    return 0;
}

On running this, the contents of the file should be outputted. Note that we don’t actually check if the file exists – however we could add this in with relative ease using is_open.

This C++ tutorial was written by


Back to C++

Advertisement: