我一直在使用read(2)和write(2)函数来读取和写入给定文件描述符的文件。
有没有这样的功能可以让您在文件中放置一个偏移量以进行读/写?
有接受文件偏移的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.
lseek()你们就会得到。
是的,您可以使用lseek():
off_t lseek(int fd, off_t offset, int whence);
该函数根据以下指令将
lseek()与文件描述符关联的打开文件的偏移量重新定位fd到参数t :offsewhence
SEEK_SET偏移量设置为偏移字节。
SEEK_CUR偏移量设置为其当前位置加上偏移量字节。
SEEK_END偏移量设置为文件大小加上偏移量字节。