Open In App

Set Position with seekg() in C++ File Handling

seekg() is a function in the iostream library that allows you to seek an arbitrary position in a file. It is included in the <fstream> header file and is defined for istream class. It is used in file handling to sets the position of the next character to be extracted from the input stream from a given file. 

Syntax: There are two syntaxes for seekg() in file handling, 



istream&seekg(streampos position);

or

istream&seekg(streamoff offset, ios_base::seekdir dir);

Parameters:



There are 3 directions we use for offset value:

Let’s understand through an example,

If we take the following input,

Input : "Hello World"

and seek to 6th position from the beginning of the file

 myFile.seekg(6, ios::beg);

and read the next 5 characters from the file into a buffer, 

char A[6];
myFile.read(A, 5);

then the output will be,

Output : World

Algorithm for the Above Example:

Program:





Output:

World

Note: If we previously get an end of file on the stream, seekg will not reset it but will return an error in many implementations. Use the clear() method to clear the end of file bit first. This is a relatively common mistake and if seekg() is not performing as expected.

 

Article Tags :
C++