Course Content
Programming in C
About Lesson

Each open file has an associated “current file offset”, normally a non-negative integer that measures the number of bytes from the beginning of the file. Read and write operations normally start at the current file offset and cause the offset to be incremented by the number of bytes read or written. By default, this offset is initialised to 0, when a file is opened, unless O_APPEND flag is specified. An open file’s offset can be explicitly set using lseek system call.

off_t lseek(int fd, off_t offset, int whence);

off_t is of signed integer type (32-bit or 64-bit depending on the machine). We need to pass the open file descriptor, offset relative to the third argument and whence which could be:

  • SEEK_SET: The file’s offset is set to offset bytes from the beginning of the file.
  • SEEK_CUR: The file’s offset is set to its current value plus the offset. The offset can be positive or negative.
  • SEEK_END: The file’s offset is set to the size of file plus the offset. The offset can be positive or negative.

On success, lseek returns the new file offset; -1 in case of error. We could seek zero bytes from the current position to determine the current offset.

off_t cur_pos = lseek(fd, 0, SEEK_CUR);
Scroll to Top