Reading and Writing, but not Sequentially

We do not always read or write a file from scratch, thus, in this lesson, we discuss how reads and writes at some offset take place.

Thus far, we’ve discussed how to read and write files, but all access has been sequential; that is, we have either read a file from the beginning to the end, or written a file out from beginning to end.

Sometimes, however, it is useful to be able to read or write to a specific offset within a file; for example, if you build an index over a text document, and use it to look up a specific word, you may end up reading from some random offsets within the document. To do so, we will use the lseek() system call. Here is the function prototype:

Press + to interact
off_t lseek(int fildes, off_t offset, int whence);

The first argument is familiar (a file descriptor). The second argument is the offset, which positions the file offset to a particular location within the file. The third argument, called whence for historical reasons, determines exactly how the seek is performed. From the man ...

Get hands-on with 1400+ tech skills courses.