Random Access

Random Access : So for we have discussed file functions that are useful for reading and writing data sequentially. In some situations, we are interested in accessing only a particular part of a file and not in reading the other parts. This can be achieved with the help of the random access functions fseek ( ), ftell ( ) and rewind ( ). Programming in C 204 The fseek ( ) function moves the file position indicator to a specific location in a stream. It takes the following form
 int fseek (FILE stream, offset, position);
where ‘stream’, is a pointer to the file concerned, ‘offset’ is a number or variable of type long and ‘position’ is an integer number. The ‘offset’ specifies the number of positions (bytes) to be moved from the location specified by ‘position’. There are three choices for the ‘position’ arguments, all of which are designated by names defined in stdio.h as follows : SEEK_SET the beginning of the file SEEK_CUR the current position of the file position indicator.
 SEEK_END  the end-of-file position.
For example,
 stat = fseek (fp, 5, SEEK_SET);
moves the file position indicator to character 5 of the stream. This will be the next character read or written. Since streams, like arrays, start at zero position, so character 5 is actually the 6 th character in the stream. The value returned by fseek ( ) is zero if the request is legal. If the request is illegal, it returns a non-zero value. The ftell ( ) function takes just one argument, which is a file pointer, and returns the current position of the file position indicator. ftell ( ) is used primarily to return a specified file position after performing one or more I/O operations. This function is useful in saving the current position of a file, which can be used later in the program. It takes the following form
 n = ftell (fp);
where n is a number of type long that corresponds to the current position i.e. n would give the relative offset (in bytes) of the current position. This means that n bytes have already been read or written. rewind ( ) takes a file pointer and resets the position of the start of the file.
For example, the statement
rewind (fp);
n = ftell (fp);

 would assign 0 to n since the file position has been set the start of the file by rewind ( ) function. This function helps us in reading or writing a file more than once, without having to close and open the file.

No comments:

Post a Comment