C++ istream::seekg() function



The C++ std::istream::seekg() function is used to change the position of the input pointer within an input stream. This function allows for random access to file data by specifying a new position, either as an absolute offset from the beginning of the file or relative to the current position or the end of the file. The position can be specified using an offset and a direction.

Syntax

Following is the syntax for std::istream::seekg() function.

istream& seekg (streampos pos);
or
istream& seekg (streamoff off, ios_base::seekdir way);

Parameters

  • pos − It indicates the new absolute position within the stream (relative to the beginning).
  • off − It indicates the offset value, relative to the way parameter.
  • way − It indicates the object of type ios_base::seekdir.

Return Value

This function returns the basic_istream object (*this).

Exceptions

If an exception is thrown, the object is in a valid state.

Data races

Modifies the stream object.

Example

In the following example, we are going to consider the basic usage of the seekg() function.

#include <iostream>
#include <sstream>
int main()
{
    std::stringstream a("TutorialsPoint");
    a.seekg(0);
    char x;
    a.get(x);
    std::cout << "Character at given position : " << x << std::endl;
    return 0;
}

Output

Output of the above code is as follows −

Character at given position : T

Example

Consider the following example, where we are going to move the get pointer to the last character in thye stream and reads it.

#include <iostream>
#include <sstream>
int main()
{
    std::stringstream a("Hi , Namaste!!");
    a.seekg(-1, std::ios::end);
    char b;
    a.get(b);
    std::cout << "Last character: " << b << std::endl;
    return 0;
}

Output

Following is the output of the above code −

Last character: !

Example

Let's look at the following example, where we are going to check the position.

#include <iostream>
#include <sstream>
int main()
{
    std::stringstream a("Welcome");
    a.seekg(3);
    std::cout << "Current position: " << a.tellg() << std::endl;
    return 0;
}

Output

If we run the above code it will generate the following output −

Current position: 3
istream.htm
Advertisements