<aside>
💡 lseek
函数用于在文件中移动文件指针。文件指针决定了下一次读或写操作的位置
</aside>
whence
参数
SEEK_SET
:将文件指针设置为距离文件开头 offset
字节的位置(offset只能是正数)SEEK_CUR
:将文件指针从当前位置移动 offset
字节(offset可正可负)SEEK_END
:将文件指针设置为距离文件末尾 offset
字节的位置(offset可正可负,但通常为负。offset为正时,可用于扩展文件长度)#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
#include <stdio.h>
int main() {
// 扩展前为10b
int fd = open("hello.txt", O_RDWR);
if(fd == -1) {
perror("open");
return -1;
}
int ret = lseek(fd, 100, SEEK_END);
if(ret == -1) {
perror("lseek");
return -1;
}
// 在扩展后的尾部写入一个空数据,使扩展后的长度生效,扩展后大小为110b
write(fd, " ", 1);
// 关闭文件
close(fd);
return 0;
}