Syntax of seekg()
The seekg() function comes in two forms, offering flexibility in how you control the "get" pointer:
stream.seekg(pos); // version 1
stream.seekg(offset, dir); // version 2
-
Version 1: Sets the get pointer position to an absolute position given by pos.
- Version 2: Sets the get pointer position to an offset given by offset, relative to the position dir.
The dir parameter can take one of the following values:
-
ios::beg - Start of the stream
-
ios::cur - Current position of the get pointer
- ios::end - End of the stream
Using seekg()
Below is a simple C++ program that demonstrates the usage of seekg():
#include <iostream>
#include <fstream>
using namespace std;
int main() {
fstream file;
file.open("test.txt", ios::in);
if(!file) {
cout << "Error in opening file!!!" << endl;
return 0;
}
// Moving pointer to end
file.seekg(0, ios::end);
// Printing position of pointer
cout << "Position of Get Pointer: " << file.tellg() << endl;
file.close();
return 0;
}
In this program, the seekg() function moves the get pointer to the end of the file, and the tellg() function then displays the current position.
Frequently Asked Questions
What is the purpose of seekg() in C++?
The seekg() function in C++ is used to change the position of the "get" pointer in an input stream.
What does ios::beg, ios::cur, and ios::end signify in seekg() function?
These are position flags representing the beginning of the stream, the current position, and the end of the stream respectively.
Can seekg() function move the get pointer outside the file boundaries?
Yes, but any attempt to read or write beyond the file boundaries leads to undefined behavior.
Conclusion
The seekg() function is a powerful tool in C++, providing control over the get pointer in file streams and enabling random access. Understanding and effectively using this function can significantly enhance your proficiency in handling file operations in C++.
Here are more articles that are recommended to read:
You can refer to our guided paths on the Coding Ninjas. You can check our course to learn more about DSA, DBMS, Competitive Programming, Python, Java, JavaScript, etc.
Also, check out some of the Guided Paths on topics such as Data Structure and Algorithms, Competitive Programming, Operating Systems, Computer Networks, DBMS, and System Design, etc. as well as some Contests, Test Series, Interview Bundles, and some Interview Experiences curated by top Industry Experts.
Happy Learning!