C语言 在偏移量处从文件描述符读取/写入
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/19780919/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Read/write from file descriptor at offset
提问by zaloo
采纳答案by paddy
回答by Sergey Podobry
There are pread/pwritefunctions that accept file offset:
有接受文件偏移量的pread/pwrite函数:
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);
回答by Darren Stone
Yes. You use the lseekfunction in the same library.
是的。您lseek在同一个库中使用该函数。
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!
祝你好运!
回答by Yu Hao
Yes, you can use lseek():
是的,您可以使用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 descriptorfdto the argumentoffset according to the directivewhenceas follows:
SEEK_SETThe offset is set to offset bytes.
SEEK_CURThe offset is set to its current location plus offset bytes.
SEEK_ENDThe offset is set to the size of the file plus offset bytes.
该
lseek()函数根据指令将与文件描述符关联的打开文件的偏移量重新定位fd到参数offsetwhence,如下所示:
SEEK_SET偏移量设置为偏移字节。
SEEK_CUR偏移量设置为其当前位置加上偏移量字节。
SEEK_END偏移量设置为文件大小加上偏移字节数。

