Seekg

Seekg

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:
#ios_base::beg (offset from the beginning of the stream's buffer).
#ios_base::cur (offset from the current position in the stream's buffer).
#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.

Example


#include
#include 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;}

Example


#include
#include

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);}


Wikimedia Foundation. 2010.

Игры ⚽ Нужно сделать НИР?

Look at other dictionaries:

  • Data file — A data file is a computer file which stores data to use by a computer application or system. It generally does not refer to files that contain instructions or code to be executed (typically called program files), or to files which define the… …   Wikipedia

Share the article and excerpts

Direct link
Do a right-click on the link above
and select “Copy Link”