在偏移处从文件描述符读/写

zal*_*loo 10 c file-descriptor

我一直在使用read(2)write(2)函数来读取和写入给定文件描述符的文件.

是否有这样的函数允许您将偏移量放入文件中进行读/写?

Ser*_*bry 15

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);
Run Code Online (Sandbox Code Playgroud)

  • 这个答案+1.对于多线程程序,`PREAD()`和`PWRITE()`是更好的,因为它们不影响文件偏移(所以多个线程可以从相同的文件描述符没有任何锁和无之间lseek的`竞争条件读()`和`read()`). (6认同)

Dar*_*one 9

是.您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 */
Run Code Online (Sandbox Code Playgroud)

祝好运!


pad*_*ddy 6

是的,您正在寻找lseek

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


Pot*_*ter 5

lseek() 你们将得到。

  • 我以为是“可爱”,你们会“找到”的。 (9认同)