ofstream

The File I/O Classes in C++

The ifstream class derives from the istream class, and enables users to access files and read data from them. The ofstream class derives from the ostream class, and enables users to access files and write data to them. The fstream class is derived from both the ifstream and ofstream classes, and enables users to access files for both data input and output. These functions are defined in the fstream header file.

Declaring input and ouput objects is simple.

#include <fstream>

using namespace std;

int main(void){

    //input stream object
    ifstream infile;

    //output stream object
    ofstream outfile;

    return 0;

}

The open() function is a member of the ifstream or ofstream class; the function in its most basic form takes a single argument, the path to the desired file. We can check the ifstream or ofstream object directly as a binary value to test whether or not the file is open and the stream is read for I/O.

As second argument that can be sent to the open() member function is the mode, which is based on a set of predefined constants. The ios::in constant opens the file for reading, and the ios::out constant opens the file for writing.

#include <iostream>
#include <fstream>

using namespace std;

int main(void){

    cout << "ios::in " << ios::in << endl;
    cout << "ios::out " << ios::out << endl;
    cout << "ios::app " << ios::app << endl;
    cout << "ios::ate " << ios::ate << endl;
    cout << "ios::trunc " << ios::trunc << endl;
    cout << "ios::binary " << ios::binary << endl;    
    

    return 0;

}

Note that the definition of the open() function uses default values.

The << and >> operators are overloaded, which means we can use them for file I/O as well as with stdin and stdout.

#include <iostream>
#include <fstream>

using namespace std;

int main(void){

    char ch;

    ifstream source;
    ofstream target;

    source.open("test.txt");

    target.open("test_copy.txt");

    if(source){
        if(target){
            while(source.get(ch)){
                target.put(ch);
            }
            source.close();
            target.close();
        }    
    }

    return 0;

}

We can use the seekg(), seekp(), tellg() and tellp() functions to enable random access of files. These functions change the position of an I/O stream pointer. The seekg() and tellg() functions are used with ifstream objects, and the seekp() and tellp() functions are used with ofstream objects.

#include <iostream>
#include <fstream>

using namespace std;

int main(void){

    ifstream infile;
    ofstream outfile;

    int i = 0;
    char ch;

    infile.open("test.txt");
    outfile.open("test_partial.txt");

    if(infile && outfile){
        infile.seekg(15);
        while(infile.get(ch)){
            outfile.put(ch);
        }
    
        infile.close();
        outfile.close();
    }

    return 0;

}

Brief Look at File Input and Output in C++

Input and output is oriented around three classes: the istream class for input, the ostream class for output, and the iostream class for input/output. As of the current standard, istream and ostream are included in the iostream class. This class provides use with three predefined variables – cin, for console input, cout, for console output, and cerr, for standard error.

The file version of the stream classes are included in the fstream header file. The input file variable is ifstream and the output file variable is ostream, meaning that the ifstream is used to read data from a file and the ofstream is used to write data to a file. We use the member function open() to open a file for reading or writing. We pass the open() function the path of the file to open.

#include <iostream>
#include <fstream>

using namespace std;

int main(void){

    ofstream writeFile;
    //create a file named Example.txt
    //int the current directory
    writeFile.open("Example.txt");
    //close the file stream
    writeFile.close();

    return 0;

}

Note that we should tell the I/O system we are done with the file via the close() member function.

We can write to and read from a file using the same statements we have been using to read from and write to cin and cout.

#include <iostream>
#include <fstream>

using namespace std;

int main(void){

    ofstream writeFile;
    writeFile.open("test2.txt");
    
    //write a line to the file
    writeFile << "Saluton Mundo!" << endl;    

    writeFile.close();

    return 0;    

}

Reading from a file is a bit trickier. We need to read the data from the file into a storage unit, such as a variable. If we know the type of data that is stored in the file this is easy to do.

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

using namespace std;

int main(void){

    int score1, score2, score3;
    //dont' forget to include
    //string header file
    string s;

    ofstream write;
    ifstream read;

    //write to file
    write.open("test3.txt");

    write << "Scores " << 85 << " " << 73 << " " << 99 << endl;

    write.close();

    //read from file
    read.open("test3.txt");

    read >> s >> score1 >> score2 >> score3;

    cout << s << " " << score1 << " " << score2 << " " << score3 << " ";
    cout << "avg. " << (score1 + score2 + score3) / 3.0 << endl;

read.close();

    return 0;    

}

We can also read from the file into a char array that acts a buffer for the data. We do this using the read() member function, which accepts two arguments, a pointer to the char array buffer and the number of characters to be read into the buffer.

#include <iostream>
#include <fstream>

using namespace std;


int main(void){

    const int buffer_size = 50;

    char buffer[buffer_size];

    ifstream read;
    ofstream write;

    write.open("test4.txt");


    write << "If mice could swim they would float with the tide and play with the fish down by the seaside. ";
    write << "The cats on the shore would quickly agree."    << endl;

    write.close();

    read.open("test4.txt");

    read.read(buffer, buffer_size-1);

    buffer[buffer_size-1] = '';

    cout << buffer;

    read.close();

    return 0;

}

When opening files for read/write, we should check to make sure that the file was opened. We can use the fail() member function to see if ifstream or ofstream is in the fail state.

#include <iostream>
#include <fstream>

using namespace std;

int main(void){

    
    ifstream read;
    read.open("doesnotexist.txt");

    if(read.fail()){
        cout << "Could not open the file." << endl;
        return 1;
    }

    return 0;

}

There’s really a lot more to file input and output than this; we’ll be looking more deeply at the subject in later posts.

As always, please take a gander at my book on C at http://www.amazon.com/Big-Als-C-Standard-ebook/dp/B00A4JGE0M/

 

 

 

 

 

Text Files and Streams

Files afford the storing of data so that they can be later be used. Today we will look at text files, which are made up of sequences of ASCII coded characters. We have already seen how the built-in streams cin and cout are used for the movement of data into and out of programs. Now, we will look at how to use file stream variables to move data between an external file and a program.

A file stream variable is an object. The class of an input file stream variable is ifstream and the class of an output file stream variable is ofstream. To call a member function of either an ifstream or ofstream object we use dot notation, which consists of the object name followed by a period followed by the name of the function we wish to call.

If we wish to use a file stream variable we must include the library file fstream.

#include <iostream>
#include <fstream>

using namespace std;

int main(void){

    ofstream writeOutput;

    //open file
    //this creates the file if it doesn't
    //already exist
    writeOutput.open("sample.txt");    

    //close file
    writeOutput.close();    

    return 0;

}

As we have just seen in the program above, an output file stream is an object of the data type ofstream. We attach the ofstream object to a particular file by passing the filename to the ofstream opbject via the open() member function. If the file does not exist, the open() member function generates it and positions the output stream pointer at the beginning of the file. If the file already exists, the open() function causes the file to be overwritten, unless we use the ofstream::app member constant to open the file in append mode.

We can check that the file open operation has been successful by calling the instance member function is_open().

#include <iostream>
#include <fstream>

using namespace std;

int main(void){

    ofstream outputStream;

    outputStream.open("test.txt");

    if(outputStream.is_open()){
        cout << "File opened successfully." << endl;
        outputStream.close();
    } else {
        cout << "Error opening file." << endl;
    }

    return 0;

}

Once a file stream has been opened for output, we can use the extraction operator, <<, to send it text.

#include <iostream>
#include <fstream>

using namespace std;

int main(void){

    ofstream output;
    
    output.open("test.txt", ofstream::app);

    if(!output.is_open()){
        cout << "Error opening file." << endl;
        return -1;
    }

    output << "Al" << "\t" << 87 << "\t" << 93 << "\t" << 84 << endl;

    output.close();

    return 0;

}

Let’s add a few more records to our test.txt file, and then we will move on to reading from files.

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

using namespace std;

struct TestScores
{
    string name;
    int score1;
    int score2;
    int score3;
};

int main(void){

    ofstream output;

    TestScores testScores[3]={
        {"Jane", 86, 95, 81},
               {"Tom", 95, 77, 91},
        {"Mary", 83, 88, 94}        
        };    

        
    output.open("test.txt", ofstream::app);

    if(!output.is_open())
    {
        cout << "Error opening file.";
        return -1;
    }    

    for(int i = 0; i < 3; i++){
        output << testScores[i].name << "\t" << testScores[i].score1 << "\t" << testScores[i].score2 << "\t";
        output << testScores[i].score3 << endl;
    }

    output.close();
    
    return 0;

}

Once we have opened a file for input, we can use the extraction operator, >>, with the stream variable in pretty much the same way we use the input stream variable cin to read input.

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

using namespace std;

int main(void){

    ifstream results;

    string name;
    int a, b, c;

    results.open("test.txt");

    if(!results){
        cout << "Error opening file." << endl;
        return -1;
    } else {
        cout << "File opened successfully." << endl;
    }

    results >> name >> a >> b >> c;

    cout << name << "\t" << a << "\t" << b << "\t" << c << endl;

    results.close();


    return 0;

}

Note that after a call to the open() member function the file pointer is set to the first item of the file.

We can use the eof() member function to test whether the end of an input file stream has been passed. The value returned by the eof() member function is 1 when we have read pas the end of the file; otherwise, the value returned is 0.

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

using namespace std;

struct TestScores{
    string name;
    int score1;
    int score2;
    int score3;
};

int main(void){

    ifstream input;
    TestScores ts;

    input.open("test.txt");

    if(!input){
        cout << "Error opening file " << endl;
        return 1;
    }


    while(!input.eof()){
        input >> ts.name >> ts.score1 >> ts.score2 >> ts.score3;
        cout << ts.name << "\t" << ts.score1 << "\t" << ts.score2 << "\t" << ts.score3 << endl;
    }

    return 0;

}

Well, that’s enough for today. Take a look at my Amazon page at http://www.amazon.com/Al-Jensen/e/B008MN382O/

 

 

 

 

Using a Text File to Print Output in C++

In everything we’ve done so far, we’ve assumed that the input to our program comes from the keyboard and that the output goes to the screen. We look now at input/output to and from files.

Our first program sends some of its output to the screen and some to a text file.

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

using namespace std;

int main(void){
    
    ofstream fout("test_output.txt");
    string s;
    int a, b;
    
    cout << "Enter a line of text, please:" << endl;
    cin >> s;
    cout << "Enter a whole number: " << endl;
    cin >> a;
    cout << "Enter another whole number: " << endl;
    cin >> b;
    
    fout << s << endl << a << " + " << b << " = " <<  a+b << endl;

    //close the output filestream
    fout.close();
    
    return 0;
    
}

We include the standard header file fstream whenever we use functions involving output files. The file created by the program will be located within the directory under which our program executes.

Again, the output path uses the current working directory as the location to create the file. A file is simply a secondary storage area used to hold information. The standard I/O header file we have been working with so far, iostream, only contains data types and variables for input and output to the monitor and from the keyboard . As we have already seen, C++ provides the fstream header file for use with file I/O; this header file contains the ifstream and ofstream data types. Note that we must declare file stream variables of type ifstream in order to receive input from a file, and ofstream in order to output from a file.

#include <fstream>
#include <iostream>

using namespace std;

int main(void){
    
    ifstream inData;

    string s;
    
    //open files
    inData.open("test_output.txt");

    inData >> s;
    
    cout << s << endl;
    
    inData.close();
    
    return 0;
    
}

Remember, the ifstream represents a stream of characters coming from an input file. We use ofstream to represent a stream of characers going to an output file.

Both ifstream variables and ofstream variables use the open() function call to open a file. Each function call accepts a string argument that contains the path to the file to be opened.

Our final program copies the contents from one file to another using an extremely primitive system of reading from ifstream into a string and then sending the string to ofstream. Unfortunately, this does not preserve whitespace! Later, we will look at more effective ways to copy files using C++.

#include <fstream>
#include <iostream>

using namespace std;

int main(void){
    
    string bufferOfSorts;
    
    ifstream inputFile;
    ofstream outputFile;
    
    inputFile.open("test_output.txt");
    outputFile.open("test_output_copy.txt");
    
    while(inputFile >> bufferOfSorts){
        outputFile << bufferOfSorts;
    }
    
    inputFile.close();
    outputFile.close();
    
    return 0;
    
}