Each type of iostream have a concept of where its "next" character would come from (if it's an IStream) or go (if it's an OS Tream). In some situations-want to move the this stream position. You can do it using the Models:one uses a absolute location in the stream called the Streampos; The second works like the standard C library functions fseek () for a file and moves a given number of bytes from the Begin Ning, end, or current position in the file.
The Streamposapproach requires that you first call a ' Tell ' FUNCTION:TELLP () for an ostreamor tellg () for an IStream. (the "P" refers to the "put pointer" and the "G" refers to the "get pointer.") This function returns a streamposyou can later with the single-argument version of SEEKP () for a ostreamor seekg () for An A istream, when you want to return to this position in the stream.
The second approach is a relative seek and uses overloaded versions of SEEKP () and SEEKG (). The first argument is the number of bytes to Move:it could be positive or negative. The second argument is the seek direction:
Ios::beg from beginning of stream
Ios::cur current position in stream
Ios::end from end of stream
Seeking.cpp
1: ". /require.h "
2: #include <iostream>
3: #include <fstream>
4: usingnamespace std;
5:
6: int main () {
7: in ("Seeking.cpp");
8: assure (in"Seeking.cpp"//File must already exist
9: in //End of file
Ten: in //Size of file
One : "File size =" << sp << Endl;
: in. SEEKG (-SP/10, ios::end);
: in . TELLG ();
+ : in //Start of file
: in //Print whole file
+ : in //Move to Streampos
: //Prints The last 1/10th of the file:
: in . Rdbuf () << Endl;
: ///:~
This program picks a file name off the command line and opens it as an ifstream. ASSERT () detects an open failure. Because This is a type of IStream, SEEKG () was used to position the "get pointer." The first call seeks zero bytes off the end of the file, which is, to the end. Because A
Streamposis a typedeffor a long, calling TELLG () at this point also returns the size of the file, which are printed out. Then a seek is performed moving the get pointer 1/10 the size of the file–notice it's a negative seek from the end of th e file, so it backs up from the end. If you try to seek positively from the end of the file, the get pointer would just stay at the end. The Streamposat that point was captured into SP2 and then a SEEKG () was performed back to the beginning of the file so the Whol E thing can is printed out using the Streambufpointer produced with Rdbuf (). Finally, the overloaded version of SEEKG () is used with the Streampos sp2to move to the previous position, and the last PO Rtion of the file is printed out.
Seeking in IOStreams