有 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);
是的。您可以在同一库中使用lseek
函数。
然后,您可以相对于文件的开头、结尾或当前位置进行任何偏移量的查找。
不要被那个库页面所吓倒。这里有一些简单的使用示例,可能是大多数人所需要的所有内容:
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 */
祝你好运!
lseek
。
http://linux.die.net/man/2/lseek
whence
控制偏移量相对于哪个位置。因此,如果您使用 SEEK_SET
请求 10 字节,则它将从文件开头开始的 10 字节。如果您随后使用 SEEK_CUR
请求 6 字节,则它将从文件开头开始的 16 字节。 - paddy是的,你可以使用lseek()
函数:
off_t lseek(int fd, off_t offset, int whence);
lseek()
函数根据指令whence
,将与文件描述符fd
相关联的打开文件的偏移量重新定位到参数offset
,具体如下:
SEEK_SET
将偏移量设置为
offset
字节。
SEEK_CUR
将偏移量设置为当前位置加上
offset
字节。
SEEK_END
将偏移量设置为文件大小加上
offset
字节。
pread()
和pwrite()
更好,因为它们不会影响文件偏移量(这样多个线程可以从同一文件描述符读取,而无需任何锁定并且不会存在lseek()
和read()
之间的竞争条件)。这个答案很棒!+1 - Thomas Perl