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\n", 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直接進行文件的拓展


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM