`pread` is a system call in Linux that allows reading data from a file descriptor at a specified offset without changing the file offset. It is part of the POSIX interface for file I/O operations and provides a way to read data atomically from a file at a specific position.
The syntax of the `pread` function in C is as follows:
```c
#include <unistd.h>
ssize_t pread(int fd, void *buf, size_t count, off_t offset);
```
Parameters:
- `fd`: The file descriptor of the file to read from.
- `buf`: A pointer to the buffer where the read data will be stored.
- `count`: The number of bytes to read.
- `offset`: The offset within the file from where the read operation should begin.
Return Value:
- If successful, `pread` returns the number of bytes read, which can be less than the requested `count` if the end of the file is reached.
- If an error occurs, `-1` is returned, and the specific error code can be obtained from the `errno` variable.
The key difference between `pread` and other file reading functions like `read` is that `pread` allows reading from a specific offset without affecting the file's current offset. This can be useful in scenarios where you want to read data from a file at a specific location without modifying the file pointer's position.
Here's an example usage of `pread`:
```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;
}
off_t offset = 100; // Read from offset 100
char buffer[100];
ssize_t bytesRead = pread(fd, buffer, sizeof(buffer), offset);
if (bytesRead == -1) {
perror("pread");
close(fd);
return 1;
}
printf("Read %zd bytes: %.*s\n", bytesRead, (int)bytesRead, buffer);
close(fd);
return 0;
}
```
In this example, the program opens a file named "file.txt" and reads 100 bytes of data starting from offset 100 using `pread`. The read data is then printed to the console.