C++ streambuf::pubseekpos() function



The C++ std::streambuf::pubseekpos() function is used to set the position of the next character to be read or written in a stream buffer. This function is often used to seek within a stream, enabling random access to different parts of the data.

This function return the new position on success or pso_type(-1) on failure.

Syntax

Following is the syntax for std::streambuf::pubseekoff() function.

pos_type pubseekpos (pos_type pos, ios_base::openmode which = ios_base::in | ios_base::out);

Parameters

  • pos &minius; It indicates the new absolute position for the position pointer.
  • which − It is generally used to determine the position on which of the controlled sequences shall be modified.

Return Value

This function returns the new position value of the modified position pointer.

Exceptions

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

Data races

It modifies the stream buffer object.

Example 1

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

#include <iostream>
#include <sstream>
int main() {
   std::stringbuf a("Welcome");
   a.pubseekpos(10);
   std::cout << a.str().substr(a.pubseekpos(2)) << std::endl;
   return 0;
}

Output

Following is the output of the above code −

lcome

Example 2

Consider the following example, where we are going to modify the stream content.

#include <iostream>
#include <sstream>
int main() {
   std::stringbuf buffer("XYZDEFG");
   buffer.pubseekpos(0);
   buffer.sputn("ABC", 3);
   std::cout << buffer.str() << std::endl;
   return 0;
}

Output

Output of the above code is as follows −

ABCDEFG

Example 3

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

#include <iostream>
#include <sstream>
int main() {
   std::stringbuf a("ABCDEFGH");
   a.pubseekpos(0);
   std::cout << a.str().substr(a.pubseekpos(6)) << std::endl;
   a.pubseekpos(0);
   std::cout << a.str().substr(a.pubseekpos(0)) << std::endl;
   return 0;
}

Output

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

GH
ABCDEFGH
streambuf.htm
Advertisements