The main drawback of sequential file containing large volume of data is that if you want to access some specific information, we have to start reading from the beginning of the file until the required information is found which may be a very time consuming job. This drawback can be removed using random access files which allow the access to a particular information randomly.
In random access files, we can access any information by skipping as many bytes as required from the current position of the file. To explain the need of random access files, consider a situation in which we want to retrieve a particular student information from a file containing multiple student information. In such a case, we only want to read the desired student information rather than going through all the student information sequentially from the beginning of the file until you reach the desired student details.
In random access files, we can access any information by skipping as many bytes as required from the current position of the file. To explain the need of random access files, consider a situation in which we want to retrieve a particular student information from a file containing multiple student information. In such a case, we only want to read the desired student information rather than going through all the student information sequentially from the beginning of the file until you reach the desired student details.
In random access files, if you want to perform read or write operation at any desired position in the file, then there is need to move the file pointer at that particular location. For this C++ I/O system provides the following functions that allows the programmer to have control over the position in the file where read or write operations can take place.
Functions | Member of class | Result |
seekg() | ifstream | Moves the set file pointer to a specific location |
seekp() | ofstream | Moves the put file pointer to a specific location |
tellg() | ifstream | Returns the current position of get file pointer |
tellp() | ofstream | Returns the current position of put file pointer |
seekg( ) and seekp( )
Both seekg( ) and seekp( ) moves the file pointer to particular location within the file. The only difference is that seekg moves the get pointer and seekp moves the put pointer which is visible from characters g and p in their names. Both seekg and seekp can take the following forms
seekg(pos);
seekp(pos);
Both these functions moves the associated file pointer to some fixed location specified by pos from the beginning of the file.
tellg( ) and tellp( )
Both these functions are used to return the current position of the associated file pointer. The tellg function provides the current position of get pointer and tellp provides the current position of the put pointer in the file. For example - if in1 is an object of ifstream class then the statement in1.telllg(); returns the current position of the get pointer.
Post a Comment