Moves to a variable position in a stream.
basic_istream<charT, traits>& seekg(pos_type); basic_istream<charT, traits>& seekg (off_type, ios_base::seekdir dir);
The function seekg is overloaded to take a pos_type object, or an off_type object (defined in basic_ios class.) The function is used to set the position of the get pointer of a stream to a random location for character extraction.
The this pointer is returned.
basic_streambuf::pubseekoff() and pubseekpos().
// The file ewl-test contains: // ABCDEFGHIJKLMNOPQRSTUVWXYZ #include <iostream> #include <fstream> #include <cstdlib> int main() { using namespace std; ifstream in("ewl-test"); if(!in.is_open()) {cout << "could not open file"; exit(1);} // note streampos is typedef in iosfwd streampos spEnd(5), spStart(5); in.seekg(spStart); streampos aCheck = in.tellg(); cout << "The offfset at the start of the reading in bytes is " << aCheck << endl; char ch; while(spEnd != spStart+10) { in.get(ch); cout << ch; spEnd = in.tellg(); } aCheck = in.tellg(); cout << "\nThe current position's offset in bytes now is " << aCheck << endl; streamoff gSet = 0; in.seekg(gSet, ios::beg); aCheck = in.tellg(); cout << "The final position's offset in bytes now is " << aCheck << endl; in.close(); return 0; }
Result:
The offfset at the start of the reading in bytes is 5 FGHIJKLMNO The current position's offset in bytes now is 15 The final position's offset in bytes now is 0