Junior — Middle
Can you explain what the system call lseek is used for in an operating system?
sobes.tech AI
Answer from AI
The lseek system call is used to change the current read/write position in an open file descriptor. This allows moving around the file, setting the pointer to a specific position from which subsequent read or write operations will be performed.
Example of using lseek in C:
#include <unistd.h>
#include <fcntl.h>
#include <stdio.h>
int main() {
int fd = open("file.txt", O_RDONLY);
if (fd == -1) {
perror("open");
return 1;
}
// Move the pointer 10 bytes from the beginning of the file
off_t offset = lseek(fd, 10, SEEK_SET);
if (offset == -1) {
perror("lseek");
close(fd);
return 1;
}
char buffer[20];
ssize_t bytesRead = read(fd, buffer, sizeof(buffer));
if (bytesRead == -1) {
perror("read");
} else {
write(STDOUT_FILENO, buffer, bytesRead);
}
close(fd);
return 0;
}
Thus, lseek allows arbitrary movement within a file, which is useful for implementing random access to data.