<aside> 💡 lseek 函数用于在文件中移动文件指针。文件指针决定了下一次读或写操作的位置

</aside>

Untitled

与标准C库fseek函数的对比

Untitled

whence参数

lseek函数的作用

  1. 移动文件指针到头文件
  2. 获取当前文件指针的位置
  3. 获取文件长度
  4. 扩展文件的长度(可实现先占用空间,之后再逐渐进行写入)

扩展文件长度案例

#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;
}