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
應用場景:
-
文件的“讀”,“寫”使用同一偏移位置
-
使用lseek獲取文件大小
-
使用lseek拓展文件的大小:要想使文件大小真正的拓展,必須要進行IO操作
可以使用truncate直接進行文件的拓展