Seeking and Moving Within Binary Files

One of the advantages of binary files is the ability to seek and move the file pointer to a specific location, which is useful for accessing specific parts of the file without reading it sequentially.

Using seekg() and seekp()

  • seekg(): Moves the file pointer for input operations (used with ifstream).
  • seekp(): Moves the file pointer for output operations (used with ofstream).

1. Seeking within Binary Files (Reading)

Here’s how to seek within a binary file and read from a specific position:

#include <iostream>
#include <fstream>
using namespace std;

int main() {
    ifstream infile("example.bin", ios::binary);

    if (!infile) {
        cout << "Error opening file!" << endl;
        return 1;
    }

    // Seek to a specific position in the file
    infile.seekg(4, ios::beg);  // Move to the 4th byte from the beginning

    int number;
    infile.read(reinterpret_cast<char*>(&number), sizeof(number));
    cout << "Read number: " << number << endl;

    infile.close();
    return 0;
}
  • seekg(4, ios::beg): Moves the input file pointer to the 4th byte from the beginning (ios::beg).

2. Seeking within Binary Files (Writing)

Here’s an example of seeking while writing to a binary file:

#include <iostream>
#include <fstream>
using namespace std;

int main() {
    ofstream outfile("example.bin", ios::binary);

    if (!outfile) {
        cout << "Error opening file!" << endl;
        return 1;
    }

    int number1 = 42;
    int number2 = 99;

    // Write data to the file
    outfile.write(reinterpret_cast<char*>(&number1), sizeof(number1));

    // Move to a specific location (offset 4 bytes) and write another number
    outfile.seekp(4, ios::beg);
    outfile.write(reinterpret_cast<char*>(&number2), sizeof(number2));

    outfile.close();
    return 0;
}
  • seekp(4, ios::beg): Moves the output file pointer to the 4th byte from the beginning, allowing you to overwrite data.