seekg()

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;

}