C语言中open函数read函数lseek函数是如何使用的

open函数的使用

函数原型

 #include <fcntl.h>

int open(const char *path, int oflag, ...);

int openat(int fd, const char *path, int oflag, ...);

用法

#include <unistd.h>
#include <fcntl.h>
#include <stdio.h>

int main(int argc, char *argv[])
{
    int fd;
    fd = open("./dict.cpp", O_RDONLY | O_CREAT, 0644);  // rw-r--r--
    printf("fd=%d
", fd);

    close(fd);
    
    return 0;
}

read函数

ssize_t read(int fd, void *buf, size_t count);

参数:

  • fd:文件描述符
  • buf:存数据的缓冲区
  • count: 缓冲区大小

返回值

  • 0:读到文件末尾
  • 成功:读到文件
  • 失败:-1,设置errno

lseek函数原型

off_t lseek(int fd, off_t offset, int whence);

参数:

  • fd:文件描述符
  • offset:偏移量
  • whence:起始偏移位置:SEEK_SET/SEEK_CUR/SEEK_END

返回值

  • 成功:较起始位置偏移量
  • 失败:-1 errno

应用场景:

  1. 文件的“读”,“写”使用同一偏移位置

  2. 使用lseek获取文件大小

  3. 使用lseek拓展文件的大小:要想使文件大小真正的拓展,必须要进行IO操作

    可以使用truncate直接进行文件的拓展

原文地址:https://www.cnblogs.com/fandx/p/12518441.html