Set Position with seekg in C++ File Handling



The setg() function sets the position of the file pointer in the file.

C++ seekg() Function

The seekg() is a function in the iostream library that allows us to seek an arbitrary position in a file. It is mainly used to set the position of the next character to be extracted from the input stream from a given file in C++ file handling.

Syntax

There are two types of syntax of seekg() function:

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

Parameters

Following is the parameter of the seekg():

  • position: It is the new position in the stream buffer.
  • offset: It is an integer value of streamoff representing the offset in the stream's buffer. It is relative to the dir parameter.
  • dir: It is a way of seeking direction. It is an ios_base::seekdir object that accepts any of the following constant values.
  • Following are the three directions we use for offset value:

  1. ios_base::beg: offset from the beginning of the stream buffer.
  2. ios_base::cur: offset from the current position in the stream buffer.
  3. ios_base::end: offset from the end of the stream buffer.

Return Value

This function returns the istream object (\*this) and changes the pointer in the file.

Example

Let's understand through a example:

Suppose we have an input: "Hello World"

Let's seek to the 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);

Output:

 World

Set Position with seekg() Function in C++

In the following example, we demonstrate the working of the seekg() function in C++:

#include <fstream>
#include <iostream>
using namespace std;

int main() {
   fstream myFile("test.txt", ios::in | ios::out | ios::trunc);

   if (!myFile) {
      cerr << "Error opening file!" << endl;
      return 1;
   }

   myFile << "tutorialspoint World";
   // Ensure data is written before reading
   myFile.flush();

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

   char A[10];
   myFile.read(A, 10);
   // null termination
   A[10] = '\0';

   cout << A << endl;

   myFile.close();
   return 0;
}

Following is the output:

point World
Updated on: 2025-05-30T18:39:14+05:30

4K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements