To retrieve data sequentially from a file, programs normally start reading from the beginning of the file and read all the data consecutively until the desired data is found. It might be necessary to process the file sequentially several times (from the beginning of the file) during the execution of a program. Both istream
and ostream
provide member functions for repositioning the file-position pointer (the byte number of the next byte in the file to be read or written). These member functions are seekg (“seek get”) for istream
and seekp (“seek put”) for ostream
. Each istream
object has a get pointer, which indicates the byte number in the file from which the next input is to occur, and each ostream
object has a put pointer, which indicates the byte number in the file at which the next output should be placed. The statement
inClientFile.seekg( 0 );
repositions the file-position pointer to the beginning of the file (location 0
) attached to inClientFile
. The argument to seekg
is a long
integer. A second argument can be specified to indicate the seek direction, which can be ios::beg (the default) for positioning relative to the beginning of a stream, ios::cur for positioning relative to the current position in a stream or ios::end for positioning relative to the end of a stream. The file-position pointer is an integer value that specifies the location in the file as a number of bytes from the file’s starting location (this is also referred to as the offset from the beginning of the file). Some examples of positioning the get file-position pointer are
// position to the nth byte of fileObject (assumes ios::beg)
fileObject.seekg( n );
// position n bytes forward in fileObject
fileObject.seekg( n, ios::cur );
// position n bytes back from end of fileObject
fileObject.seekg( n, ios::end );
// position at end of fileObject
fileObject.seekg( 0, ios::end );
The same operations can be performed using ostream
member function seekp
. Member functions tellg and tellp are provided to return the current locations of the get and put pointers, respectively. The following statement assigns the get file-position pointer value to variable location
of type long
:
location = fileObject.tellg();