美文网首页
Linux中的lseek

Linux中的lseek

作者: brownfeng | 来源:发表于2020-02-01 17:41 被阅读0次

    Linux中的lseek

    lseek函数用来重新定位文件的读写位置.

    我们在linux编程中使用的文件描述符int fd, 在系统层会创建一个结构体,底层维护fd对应打开文件(linux中一切皆文件)的相关属性,其中一个非常关键的是文件读写位置offset.

    #include <sys/types.h>
    #include <unistd.h>
    off_t lseek(int fd, off_t offset, int whence);
    

    offset为正则向文件末尾移动(向前移),为负数则向文件头部(向后移)。

    lseek()函数会重新定位被打开文件的位移量,根据参数offset以及whence的组合来决定:

    SEEK_SET:
      从文件头部开始偏移offset个字节
    SEEK_CUR:
      从文件当前读写的指针位置开始,增加offset个字节的偏移量
    SEEK_END:
      文件偏移量设置为文件的大小加上偏移量字节.

    lseek常见两个作用:

    1. readwrite函数掉过过程中,移动cur pos位置
    2. 直接将fd背后的cur pos移动到文件末尾, lseek返回的是文件的长度.

    实例:

    #include <fcntl.h>
    #include <stdio.h>
    #include <sys/stat.h>
    #include <sys/types.h>
    #include <unistd.h>
    
    int main(int argc, char *argv[]) {
      if (argc != 2) {
        printf("./a.out filename\n");
        return -1;
      }
    
      int fd = open(argv[1], O_RDWR | O_CREAT, 0666);
      /// file offset changed!!!
      write(fd, "helloworld", 10);
      char buf[256] = {0};
      /// reset fd pos
      lseek(fd,0, SEEK_SET);
      int ret = read(fd, buf, sizeof(buf));
      if (ret) {
        write(STDOUT_FILENO, buf, ret);
      }
      close(fd);
      return 0;
    }
    

    相关文章

      网友评论

          本文标题:Linux中的lseek

          本文链接:https://www.haomeiwen.com/subject/lwexxhtx.html