Read/write from file descriptor at offset

会有一股神秘感。 提交于 2019-11-28 03:14:27

问题


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?


回答1:


Yes, you're looking for lseek.

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




回答2:


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



回答3:


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!




回答4:


lseek() and ye shall  receive.




回答5:


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.



来源:https://stackoverflow.com/questions/19780919/read-write-from-file-descriptor-at-offset

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