The seek system call (commonly used via the function lseek() in C) is used to change the file offset (read/write position) of an open file descriptor in Unix-like operating systems.
Syntax (in C):
#include <unistd.h>
off_t lseek(int fd, off_t offset, int whence);
Parameters:
fd: The file descriptor of the open file.
offset: A value (possibly negative) indicating the number of bytes to move the file offset.
whence: Indicates what the offset is relative to. It can be:
SEEK_SET: Set the offset to offset bytes from the beginning of the file.
SEEK_CUR: Set the offset to the current position plus offset.
SEEK_END: Set the offset to the size of the file plus offset.
Return Value:
- On success: returns the resulting offset (in bytes) from the beginning of the file.
- On failure: returns
-1 and sets errno appropriately.
Example:
#include <stdio.h>
#include <unistd.h>
#include <fcntl.h>
int main() {
int fd = open("test.txt", O_RDONLY);
if (fd < 0) {
perror("open");
return 1;
}
// Move to the 10th byte from the beginning
off_t pos = lseek(fd, 10, SEEK_SET);
if (pos == -1) {
perror("lseek");
return 1;
}
printf("New file offset: %ld\n", pos);
close(fd);
return 0;
}
What lseek is used for:
- Random file access (e.g., move to a specific data point in a large file).
- Skipping data.
- Getting the length of a file (by seeking to the end).
- Modifying file size (in combination with write).
- Sparse file creation (by seeking beyond the end and writing, creating "holes").
Important Notes:
lseek() does not read or write any data; it only changes the file pointer.
- Not all file descriptors support seeking (e.g., pipes, sockets). If you try to seek on such files, it will fail with
ESPIPE error (Illegal seek).
In summary, the seek syscall (lseek) manipulates where in a file the next read or write will happen.