Home » Learn C++ » Seekg Function in C++

Seekg Function in C++

The “Seekg” Function:

            The “seekg” stands for seek get. This function is used to seek & get the file pointer position (the byte number of the next byte) from where the next data of the file is to he read.

            The general syntax of this function is:

object.seekg (pos);

 

Where:
object: represents the created object of ifstream (or fstream).

seekg: represents the member function of the object.

pos: represents position (the byte number of next byte) from which the next data of the tile is to be read. It is a long int type parameter.

 

            For example, to position the file pointer from the beginning of the file to the position number 10 (10th byte) in the file to read the next data, the function is written as:

object.seekg (10);

 

            If the file has a group of records and each record has a length of 60 bytes then the size of record is multiplied with the above parameter to reach the position of the specific record. Thus the above statement is written as:

object.seekg (10*60);

 

            The file position pointer can be set to get the data from the file relative to the beginning of the file, end of the file or from the current file pointer position of the file. So the second syntax of “seekg” function is:

object.seekg (pos, rp);

 

Where
object & pos: these are same as mentioned in the first syntax of seekg function.

rp: represents the relative position.

            For example, to seek the file pointer position 10 bytes (for reading data) relative to the beginning of the file, the function is written as:

object.seekg (10, ios : : beg);

 

            Similarly, to seek the file pointer position 10 bytes (for reading data) relative to the current position of file pointer in the tile, the function is written as:

object.seekg (10, jog : : cur);

 

            And to seek the file pointer position 10 bytes (for reading data) back relative to the end of file, the function is written as:

object.seekg (-10, ios : : end);

 

Note: The beg cur and end are not available in some compilers.

 

Other Topics

comment closed

Get Adobe Flash playerPlugin by wpburn.com wordpress themes
Copyright © 2010 Information Village. All rights reserved.