On Linux, 'pread()' does the trick:
ssize_t pread(int fd, void *buf, size_t count, off_t offset);
It will seek to 'offset', and then read 'count' bytes int 'buf'.
Question
I need to read a specific set of bytes from a file type for a project I'm working on.
For example, let's say we have the following open file called "image":
int fd = open(image, O_RDWR, S_IRWXU);
Let's say I needed to read a specific section of this file starting from an offset from the beginning, say, a section starting at 1024 bytes and ending at 2048 bytes into the file.
I know we have read(),
int rd = read(fd, &example, sizeof(1024));
and this would read into "example", the first 1024 bytes.
I know fseek exists, which would set a pointer starting where I want to start reading into "example", but only if I have a FILE type, right? I currently only have a name and it's fd,
char *image;
int fd;
Can I use file_name or fd in fseek? Or is there a better way to do this?
Solution
On Linux, 'pread()' does the trick:
ssize_t pread(int fd, void *buf, size_t count, off_t offset);
It will seek to 'offset', and then read 'count' bytes int 'buf'.
OTHER TIPS
lseek
is the equivalent function to fseek
, using file descriptors instead of FILE
pointers. You can also use pread
as Mahonri Moriancumer noted.