Read/write from file descriptor at offset

守給你的承諾、 提交于 2019-11-29 10:47:22

Yes, you're looking for lseek.

http://linux.die.net/man/2/lseek

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);

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!

lseek() and ye shall  receive.

Yes, you can use lseek():

off_t lseek(int fd, off_t offset, int whence);

The lseek() function repositions the offset of the open file associated with the file descriptor fd to the argument offset according to the directive whence as follows:

SEEK_SET

The offset is set to offset bytes.

SEEK_CUR

The offset is set to its current location plus offset bytes.

SEEK_END

The offset is set to the size of the file plus offset bytes.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!