What is Random Access to Files
So far we have discussed file functions that are useful for
reading and writing data sequentially. There are occasions, however, when 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 functions fseek, ftell, and rewind available in the I/O library.
ftell
ftell takes a
file pointer and return a number of type long,
that corresponds to the current position. 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 );
n would give the
relative offset ( in bytes ) of the current. This means that n bytes have already been read ( or
written ).
rewind
rewind takes a
file pointer and resets the position to the start of the file. For example, the
statement
rewind ( fp ) ;
n = ftell (
fp ) ;
would assign 0 to
n because the file position has been
set to the start of the file by rewind. Remember,
the first byte in the file is numbered as 0, second as 1, and so on. This
function helps us in reading a file more than once, without having to close and
open the file. Remember that whenever a file is opened for reading or writing,
a rewind is done implicitly.
fseek
fseek function is
used to move the file position to a desired location within the file. It takes
the following form:
fseek ( file_ptr, offset, position ) ;
file_ptr 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 the position. The position can
take one of the following three values :
The offset may be positive,
meaning move forwards, or negative, meaning move backwards.
Post a Comment