C++: Basic File Input and Output

Basic File Input and Output

In this C++ video tutorial, we demonstrate how to read from and write to a file via STL file streams. We used ifstream to receive input from a file and ofstream to send output to a file. These are input file streams and output file streams, respectively.

As we demonstrated in the video, we can access a file via the file name if the file is in the same folder as our Visual C++ project file. However, if we want to access a file in another location, we can do this using the full path and file name. It is important to remember that the backslash character (\) is an escape character, so it must be doubled when it is used in a string literal, as we do in the program below.

#include <iostream>
#include <fstream>
#include <string>

int main() {
    using namespace std;

    // Output to a file
    ofstream qOutFile("C:\temp\XoaX.txt");

    if (!qOutFile.good()) {
        cout << "Could not open the file for output!" << endl;
        return 1;

    // A couplet from Alexander Pope's "An Essay on Man"
    string qLine1("If white and black blend, soften and unite");
    string qLine2("a thousand ways, is there no black or white?");

    qOutFile << qLine1 << endl;
    qOutFile << qLine2;


    // Read the text back from the file
    ifstream qInFile("C:\temp\XoaX.txt");
    string qWord;

    if (!qInFile.good()) {
        cout << "Could not open the file for input!" << endl;
        return 1;

    while (!qInFile.eof()) {
        qInFile >> qWord;
        cout << qWord << " ";
    cout << endl;


    return 0;

In the program above, we open a file for output and then write a couplet from Alexander Pope’s "An Essay on Man" to it. In the next section of code, we read back the couplet from the file. When we write the text, it is written out as two lines. When we read it back we read back each string individually. Recall that when we read a string, the white space only serves as a delimiter, which is thrown out. Therefore, we needed to add spaces when we wrote the text to the console window so that it would come out looking nice.

Above we have the file that we wrote out. When we write to a file, the file will be created if it does not already exist. So, do not need to worry about creating a file beforehand. However, we still check that our file was opened by checking the return value of the good() function. This is necessary because writing the file can fail for other reasons. For example, you might be trying to write to a folder for which you do not have write permission.

Above, we have the output of the program in the console window. The spaces we not actually read from the file, but were added in to the console output after the strings were read.