SEEKG()
This is used to reposition the get pointer (read pointer) within a file stream. It allows programmers to move the pointer to a specific location in the file, enabling precise control over where data is read from. It is particularly useful when you need to skip a certain number of bytes, revisit previously read sections, or access data at a known offset. By combining seekg() with the tellg() function, which reports the current position of the get pointer, developers can implement efficient file navigation and random access operations, making it an essential tool for reading structured or binary files.
// Move get pointer to an absolute position
istream& seekg(streampos pos);
// Move get pointer relative to a specific direction
istream& seekg(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() {
ifstream file("example.txt");
if (file.is_open()) {
// Move the read pointer to the 5th byte from the beginning
file.seekg(5);
// Read from the new position
char ch;
file.get(ch);
cout << "Character at position 5: " << ch << endl;
file.close();
} else {
cout << "Unable to open file!" << endl;
}
return 0;
}
* seekg(5) moves the read pointer to the 5th byte, and then get(ch) reads
the character at that position.
EXAMPLE
WORD EXTRACTION
Last updated