All i/o streams objects have, at least, one internal stream pointer:
ifstream, like istream, has a pointer known as the get pointer that points to the element to be read in the next input operation.
ofstream, like ostream, has a pointer known as the put pointer that points to the location where the next element has to be written.
Finally, fstream, inherits both, the get and the put pointers, from iostream (which is itself derived from both istream and ostream).
These internal stream pointers that point to the reading or writing locations within a stream can be manipulated using the following member functions:
tellg() and tellp()
These two member functions have no parameters and return a value of the member typepos_type, which is an integer data type representing the current position of the get stream pointer (in the case oftellg) or the put stream pointer (in the case of tellp).
seekg() and seekp()
These functions allow us to change the position of the get and put stream pointers. Both functions are overloaded with two different prototypes. The first prototype is:
seekg ( position );
seekp ( position );
Using this prototype the stream pointer is changed to the absolute position position (counting from the beginning of the file). The type for this parameter is the same as the one returned by functionstellg andtellp: the member type pos_type, which is an integer value.
The other prototype for these functions is:
seekg ( offset, direction );
seekp ( offset, direction );
Using this prototype, the position of the get or put pointer is set to an offset value relative to some specific point determined by the parameterdirection.offset is of the member type off_type, which is also an integer type. Anddirection is of typeseekdir, which is an enumerated type (enum) that determines the point from where offset is counted from, and that can take any of the following values:
ios::beg offset counted from the beginning of the stream
ios::cur offset counted from the current position of the stream pointer
ios::end offset counted from the end of the stream
==============================================================
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 -- Append to the file
ios::ate -- Set the current position to the end
ios::trunc -- Delete everything in the file
For example:
ofstream a_file ( "test.txt", ios::app );
This will open the file without destroying the current contents and allow you to append new data. When opening files, be very careful not to use them if the file could not be opened. This can be tested for very easily:
ifstream a_file ( "example.txt" );
if ( !a_file.is_open() )
{
// The file could not be opened
}
else
{
// Safely use the file stream
}