Seeking Within a File

The last example showed a program that sequentially read through the /etc/motd file, copying it to standard output. Sometimes it is necessary to access portions of a file randomly. Perhaps your file represents a series of a million fixed-length records that must be retrieved at random. UNIX provides this functionality in the form of the lseek(2) function.

Applying lseek(2)

The lseek(2) function is actually a dual-purpose function. It not only allows the program to seek a specified offset within the open file, but the program can also find out what the current offset is, within the specified file. The function synopsis for lseek(2) is as follows:

 #include <sys/types.h> #include <unistd.h> off_t lseek(int fildes, off_t offset, ...

Get Advanced UNIX Programming now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.