Types of Files
- So far we have assumed that our files were sequential:
sucessive reads or writes read or write from sucessive bytes in the file.
While this is a very good model of some files (the keyboard or a file on
a tape drive), it is a limited model of others (files stored on a disk
drive or cd rom). These other files support random access: they
can quickly and easily be read or written starting from any byte in the
file.
- The following routines are defined in stdio.h and
may be used on random access files:
- void rewind(FILE *); is easy. It rewinds the file to
the beginning -- all further reads or writes take place starting at
the beginning of the file.
- long int ftell(FILE *); returns the current byte location
of the "read-write head" in the current file. For example, if you
have read 123 bytes from the file testfile, ftell(testfile)
returns 123.
- int fseek(FILE *, long int offset, int whence); has three
different behaviours, depending on whether whence is 0, 1, or 2.
If whence is 0, then fseek moves the read-write head
to position offset. If whence is 1, then fseek
moves the read-write head to the current position plus offset.
If whence is 2, then fseek moves the read-write head
to the position of the end of the file plus offset. (offset
is definitely allowed to be negative.)
Next Slide