Open In App

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

Last Updated : 05 Apr, 2022
Improve
Improve
Like Article
Like
Save
Share
Report

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:

  • position: is the new position in the stream buffer.
  • offset: is an integer value of type streamoff representing the offset in the stream’s buffer. It is relative to the dir parameter.
  • dir: It is the seeking direction. It is an object of type ios_base::seekdir that can take any of the following constant values.

There are 3 directions we use for offset value:

  • ios_base::beg: offset from the beginning of the stream’s buffer.
  • ios_base::cur: offset from the current position in the stream’s buffer.
  • ios_base::end: offset from the end of the stream’s buffer.

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:

  • Open a new file for input/output operations, discarding any current in the file (assume a length of zero on opening).
  • Add the characters “Hello World” to the file.
  • Seek to 6 characters from the beginning of the file.
  • Read the next 5 characters from the file into the buffer.
  • End the buffer with a null terminating character.
  • Output the contents read from the file and close it.

Program:

CPP





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.

 


Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads