The ostream class is defined under the standard header library iostream.h, and it has methods for handling outputs in C++. It is used to write data to output locations such as files and console windows.
This tutorial will cover how to use ostream::seekp(pos) method.
How to Use ostream::seekp(pos) Method in C++ with Examples
When the file is created or an already saved file is opened, the pointer is located at the 0 position. So, to write in it, we have to overwrite the whole text. The ostream::seekp(pos) method in C++ is used to fix the pointer position specified to the new position in the output sequence. Hence, it enables the user to write in the desired position, indicating the index, without overwriting the whole text.
Syntax
The syntax for the ostream::seekp(pos) method in C++ is given as:
Parameters
The new position is given as a parameter in this method.
Return Value
The return value for this method is the ostream object with a new set position to the specific position.
Example
This example illustrates the use of ostream::seekp(pos) method in C++:
#include <iostream>
using namespace std;
int main () {
long pos;
ofstream outfile;
outfile.open ("test.txt");
outfile.write ("How to Same",11);
pos=outfile.tellp();
outfile.seekp (pos - 4);
outfile.write ("Tam",3);
outfile.close();
return 0;
}
In this program, a file test.txt is opened and will create a file if the file is not present, and in the opposite case it will be overwritten. To store the pointer’s current position, a variable named pos is declared. The text is written in the file and the tellp() function is called to get the current position of the pointer. The seekp(pos – 4) function is used to access the position of the pointer, moving it 4 spaces backward. The total number of positions is 11, so it will point to position number 7. Then the. write command is used to overwrite at this position for 3-digit places. In the end, the file is closed.
The text file that was called in the program named test is overwritten at the position indicated by the pointer using the seekp() function.
Conclusion
The ostream class is defined under the standard header library iostream.h, and it has methods for handling outputs in C++. It is used to write data to output locations such as files and console windows. The ostream::seekp(pos) method in C++ is used to fix the pointer position specified to the new position in the output sequence. Hence, it enables the user to write in the desired position, indicating the index, without overwriting the whole text.