Download C++ Library Reference - Oracle Documentation
Transcript
When you open a file by providing its name to one of the fstream constructors or
by using the open function, the file is automatically closed when the fstream is
destroyed (by a delete or when it goes out of scope). When you attach a file to an
fstream, it is not automatically closed.
3.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.
■
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.
3-14
C++ Library Reference • May 2000