C++ Library Reference

Repositioning within a File

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

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 is not portable, but you can always return to a previously saved streampos value.