seekg() function in File Handling in C++

Hey Guys, in this tutorial, you would understand what seekg() function does in File Handling in C++.

seekg() Function in File Handling in C++

So as I explained in my previous tutorial,
We have a function named seekg() that we can use, specifically for FIle Handling, when we import the fstream package.

So what does seekg() do?
Just like seekp(), seekg() moves the pointer to the desired location.
So what is the difference between seekp() and seekg()?
seekp() moves the put pointer to the desired location i.e. for write operation.
seekg() moves the get pointer to the desired location i.e. for read operation.

When we try reading a text file, the pointer is set to 0.
So we read from the 0th pointer all the way to the last pointer.

But if we want to read from a particular pointer, we use seekg().
Using seekg() we navigate to the desired location in the text file and read from thereon.

Note: Pointer value starts from 0

Syntax: seekg() function in C++

The syntax of seekg() function is given below:


obj is our file handling object and 6 is the position we would like to set our pointer to.

C++ Code example: seekg()

Take a look at the following code:

#include <fstream>
#include <iostream>
using namespace std;
int main () 
   fstream obj;"test.txt", ios::in);
   int pos=6;
        char ch;

Let us take a look at the code line by line.

  1. fstream obj;
    Here we are using the function fstream that enables read and write on a particular file.
    obj is the object we are using to refer to fstream.
  2. (“test.txt”, ios::in);
    Here we are opening a text file called test with basic function to read hence the “ios::in”.
  3. int pos=6;
    Here we are defining a variable pos of type int and storing the value 6 in it.
    We will use this to move to the 6th position.
  4. obj.seekg(pos);
    Using the above syntax, we are moving to the 6th position in the test file.
    I have “Hello World” stored in my test file.
    When we move to the 6th position we reach “W” in World.
  5. while(!obj.eof())
    char ch;
    This is the basic code to read the text file. You are reading from the position you set it to, all the way till the end of the file.
    Once we reach the end of the file, the while loop exits.
  6. obj.close();
    And Finally, here we are closing the text file.

I had “Hello World” written in my text file.
After executing the above code, my output is:


This function is useful especially when we know the position where we want to start reading from.
And hence we have covered seekg() function in C++

Also read: seekp() function in File Handling in C++

Leave a Reply

Your email address will not be published. Required fields are marked *