1. open函数
- 函数原型:
int open(const char *pathname,int flags);
int open(const char *pathname,int flags,mode_t mode);
- pathname : 文件的相对或者绝对路径
- flags:打开方式
- 必选项(三种方式之间是互斥的)
- O_RDONLY:只读打开
- O_WRONLY:只写打开
- O_RDWR:可读可写打开
- 可选项
- O_APPEND:表示追加,加附到文件末尾,不覆盖原数据
- O_CREAT:若此文件不存在则创建它,需提供第三个参数mode:表示该文件的访问权限
- 文件权限由open的mode参数和当前进程的umask掩码共同决定:
mode&~umask
- 文件权限由open的mode参数和当前进程的umask掩码共同决定:
- O_EXCL:如果同时指定了O_CREAT,并且文件已经存在,则出错返回
- O_TRUNC:如果文件已经存在,则将其长度截断(Truncate)为0字节
- O_NINBLOCK:设置文件为非阻塞状态
- 必选项(三种方式之间是互斥的)
- 常见错误:
- 打开文件不存在
- 以写方式打卡只读文件(打开文件没有对应的权限)
- 以只写方式打开目录
code:
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
#include <stdlib.h>
#include <iostream>
using namespace std;
int main(){
//打开一个文件test
int fd = open("test",O_RDWR | O_CREAT,0777);
if(fd == -1){
perror("open error");
exit(1);
}
close(fd);
return 0;
}
2. close函数
- 参数:open函数的返回值
- 返回值
- 0 :正常关闭
- -1:关闭出现错误
3. read函数
- 从打开的设备或文件中读取数据
- 函数原型:
ssize_t read(int fd, void *buf,size_t