You can alter the reading and writing position in a file. Several tools are supplied for this purpose.
streampos is a type that can record a position in an iostream.
tellg (tellp) is an istream (ostream) member function that reports the file position. Since istream and ostream are the parent classes of fstream, tellg and tellp can also be invoked as a member function of the fstream class.
seekg (seekp) is an istream (ostream) member function that finds a given position.
The seek_dir enum specifies relative positions for use with seek.
enum seek_dir {beg=0, cur=1, end=2}; |
For example, given an fstream aFile:
streampos original = aFile.tellp(); //save current position aFile.seekp(0, ios::end); //reposition to end of file aFile << x; //write a value to file aFile.seekp(original); //return to original position |
seekg (seekp) can take one or two parameters. When it has two parameters, the first is a position relative to the position indicated by the seek_dir value given as the second parameter. For example:
aFile.seekp(-10, ios::end); |
moves to 10 bytes from the end while
aFile.seekp(10, ios::cur); |
moves to 10 bytes forward from the current position.
Arbitrary seeks on text streams are not portable, but you can always return to a previously saved streampos value.