Sun Studio 12: C++ User's Guide

14.4.1.5 Repositioning Within a File

You can alter the reading and writing position in a file. Several tools are supplied for this purpose.


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.


Note –

Arbitrary seeks on text streams are not portable, but you can always return to a previously saved streampos value.