Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Read/write from file descriptor at offset

I've been using the read(2) and write(2) functions to read and write to a file given a file descriptor.

Is there any function like this that allows you to put an offset into the file for read/write?

like image 750
zaloo Avatar asked Nov 05 '13 02:11

zaloo


People also ask

What is offset in file reading?

To access a text file we have to create a filehandle that will make an offset at the beginning of the text file. Simply said, offset is the position of the read/write pointer within the file. offset is used later on to perform operations within the text file depending on the permissions given, like read, write, etc.

Does write () Change offset?

write() : Will write data to the file at the offset specified. If the write is past the end-of-file, the file will be resized with padding zeros.

Does read Change offset?

A successful read() changes the file offset by the number of bytes read. If read() is successful and nbyte is greater than zero, the access time for the file is updated.

What is file offset in Linux?

An offset into a file is simply the character location within that file, usually starting with 0; thus "offset 240" is actually the 241st byte in the file.


2 Answers

There are pread/pwrite functions that accept file offset:

ssize_t pread(int fd, void *buf, size_t count, off_t offset);
ssize_t pwrite(int fd, const void *buf, size_t count, off_t offset);
like image 94
Sergey Podobry Avatar answered Sep 30 '22 17:09

Sergey Podobry


Yes. You use the lseek function in the same library.

You can then seek to any offset relative to the start or end of file, or relative to the current location.

Don't get overwhelmed by that library page. Here are some simple usage examples and probably all most people will ever need:

lseek(fd, 0, SEEK_SET);   /* seek to start of file */
lseek(fd, 100, SEEK_SET); /* seek to offset 100 from the start */
lseek(fd, 0, SEEK_END);   /* seek to end of file (i.e. immediately after the last byte) */
lseek(fd, -1, SEEK_END);  /* seek to the last byte of the file */
lseek(fd, -10, SEEK_CUR); /* seek 10 bytes back from your current position in the file */
lseek(fd, 10, SEEK_CUR);  /* seek 10 bytes ahead of your current position in the file */

Good luck!

like image 20
Darren Stone Avatar answered Sep 30 '22 16:09

Darren Stone