Seekg

From Wikipedia, the free encyclopedia

In the C++ programming language, seekg is a function in the fstream library that allows you to seek to an arbitrary position in a file.

istream&  seekg ( streampos position );
istream&  seekg ( streamoff offset, ios_base::seekdir dir );
  • position is the new position in the stream buffer. This parameter is an object of type streampos.
  • offset is and integer value of type streamoff representing the offset in the stream's buffer. It is relative to dir parameter.

dir is the seeking direction. It is an object of type ios_base::seekdir that can take any of the following constant values:

  1. ios_base::beg (offset from the beginning of the stream's buffer).
  2. ios_base::cur (offset from the current position in the stream's buffer).
  3. ios_base::end (offset from the end of the stream's buffer).

Note: If you have previously got an end of file on the stream, seekg will not reset it but will return an error in many implementations. - use the clear() method to clear the end of file bit first. This is a relatively common mistake and if seekg() is not performing as expected, it is wise to clear the fail bit, as shown below.

[edit] Example

#include <iostream>
#include <fstream>
using namespace std;
 
int main () {
  char buffer[10];
 
  fstream aFile;   //input file
  aFile.open ("test.txt", ios::binary );
  aFile << "hello"; // inserts "hello" into the file
 
  //seek to 3 characters from the beginning of the file
  aFile.seekg (3, ios::beg); 
  aFile.read (buffer,2); //read two characters into the buffer
  buffer[3]=0; // end buffer with the null terminating character
  aFile.close();
 
  cout << buffer;
}

[edit] Example

#include <iostream>
#include <fstream>
 
int main () {
 string line;
 while (! myfile.eof())
 {
   /* this do-while loop continually overwrites string "line" with the next line from myfile
      until eof is reached. */
   getline(myfile,line);
 }
 
 // without this line, seekg() is ineffective, as the fail bit is still there
 myfile.clear();
 
 myfile.seekg(0);
}