SEEKP()

This is used with output file streams, such as ofstream, to reposition the put pointer (write pointer) within a file. This function allows programmers to control exactly where data will be written, making it possible to overwrite specific sections of a file or skip ahead to a desired location. By specifying a byte offset, for example seekp(5), the put pointer is moved to the fifth byte from the beginning of the file. seekp() can also take a second parameter to specify the reference point—beginning, current position, or end of the file—providing precise control over file writing operations and enabling efficient random access when modifying files.

// Move put pointer to an absolute position
ostream& seekp(streampos pos);

// Move put pointer relative to a specific direction
ostream& seekp(streamoff off, ios_base::seekdir dir);

 * streampos pos — an absolute position in the file from the beginning.
 * streamoff off — a byte offset.
 * ios_base::seekdir dir — the reference point for the offset; can be:
    - ios::beg — beginning of the file
    - ios::cur — current position
    - ios::end — end of the file
#include <iostream>
#include <fstream>
using namespace std;

int main() {
    ofstream file("example.txt");

    file << "Hello, this is the start of the file.\n";

    // Move the write pointer to the 10th byte
    file.seekp(10);
    file << "INSERTED";

    file.close();
    return 0;
}

 * Writes an initial sentence to the file.
    - seekp(10) moves the write pointer to the 10th byte from the beginning.
    - "INSERTED" is written starting at the 10th byte, overwriting part of the original content.
    - Final file content would be - Hello, thiINSERTEDt of the file.

CORRECTING DATA IN A FILE

Last updated