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?

有帮助吗?

解决方案

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'.

其他提示

lseek is the equivalent function to fseek, using file descriptors instead of FILE pointers. You can also use pread as Mahonri Moriancumer noted.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top