Seekg

Last updated

In the C++ programming language, seekg() is a function in the <fstream> header of the C++ Standard Library for seeking to an arbitrary position in a file. This function is defined for std::ifstream class, for std::ofstream class there is a similar function seekp() (this is to avoid conflicts in case of classes that derive both std::istream and std::ostream, such as std::iostream).

namespacestd{istream&seekg(streamposposition);istream&seekg(streamoffoffset,ios_base::seekdirdir);}

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

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

Note: If the end of file on the stream has previously been reached, seekg will not reset it but will return an error in many implementations. To clear the end of the file bit first, use the clear() method. 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.

Example of seekg

importstd;usingstd::fstream;usingstd::ios;intmain(){// Open a new file for input/output operations discarding any current// content in the file (assumes a length of zero on opening)fstreammyFile("test.txt",ios::in|ios::out|ios::trunc);// Add the characters "Hello World" to the filemyFile<<"Hello World";// Seek to 6 characters from the beginning of the filemyFile.seekg(6,ios::beg);// Read the next 5 characters from the file into a buffercharbuffer[6];myFile.read(buffer,5);// End the buffer with a null terminating characterbuffer[5]=0;// Output the contents read from the file and close it std::println(buffer);myFile.close();}

Example clearing the fail bit

importstd;usingstd::ifstream;usingstd::ios;usingstd::string;intmain(){stringline;// Creates a new ifstream object and associates it with a file passed in via the parameters.// The object is then checked to see if the end-of-file has been reached, if the file has data// then this will be false.ifstreammyFile(argv[1],ios::in);std::println(myFile.eof());// Continuously loops over each line of the file until the end of the filewhile(!myFile.eof()){std::getline(myFile,line);}// Again outputs the end-of-file status for the stream, this time the answer will be truestd::println(myFile.eof());// Seeks to the very beginning of the file, clearing any fail bits first (such as the end-of-file bit)myFile.clear();myFile.seekg(0,ios::beg);// Outputs the status of the stream again, the result will be falsestd::println(myFile.eof());myFile.close();}