In the last section you have learned how to read or write data sequentially
to an opened disk file. However, in some other cases, you need to access
particular data somewhere in the middle of a disk file. To do so, there are
I/O functions that are designed to deal with random access:
fseek, ftell and rewind.
The fseek function offers you the possibility to move the
file position indicator to the spot you want to access in a file. The
syntax is:
#include <stdio.h> int fseek(FILE *stream, long offset, int whence);
stream is the file pointer associated with an opened file.
offset indicates the number of bytes from a fixed position
specified by whence that can have one of the following values:
SEEK_SET, SEEK_CUR, and SEEK_END.
If it is successful, the function returns 0;
otherwise, the function returns a nonzero value.
If SEEK_SET is chosen, the offset is counted from the beginning
of the file, and the value of offset should be greater than
or equal to zero. If SEEK_END is used, the offset starts from
the end of the file, and the value of offset should be negative.
When SEEK_CUR is used, the offset is calculated from the current
value of the file position indicator.
You can obtain the current value of the file position indicator by calling
the ftell function.
#include <stdio.h> int ftell(FILE *stream);
The value returned by ftell represents the number of bytes
from the beginning of the file to the current position pointed to by the
file position indicator.
If the function fails, it returns –1L
(that is, a long value of minus 1).
Sometimes you might want to reset the file position indicator and put it
at the beginning of a file. To do this you have the rewind
function.
#include <stdio.h> void rewind(FILE *stream);
So, the following statement:
rewind(f_ptr);is equivalent to this:
fseek(f_ptr,0L,SEEK_SET);