open函数可以打开或创建一个文件,close 函数就是关闭文件了。
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
int open(const char *pathname, int flags);
int open(const char *pathname, int flags, mode_t mode);
返回值:成功则返回新分配的文件描述符,出现错误就返回 -1
flag 参数有多种选择:
必选项:
- O_RDONLY 只读打开
- O_WRONLY 只写打开
- O_RDWR 可读可写打开
可选项:
- O_APPEND 表示追加。如果文件已有内容,这次打开文件所写的数据附加到文件的末尾而不覆盖原来的内容。
- O_CREAT 若此文件不存在则创建它。使用此选项时需要提供第三个参数mode,表示该文件的访问权限。
- O_EXCL 如果同时指定了O_CREAT,并且文件已存在,则出错返回。
- O_TRUNC 如果文件已存在,并且以只写或可读可写方式打开,则将其长度截断(Truncate)为0字节。
- O_NONBLOCK 对于设备文件,以O_NONBLOCK方式打开可以做非阻塞I/O(Nonblock I/O)
mode参数:
指定文件权限,4位数字,第一位一般是0 后面三位是 r w x 4 2 1 一般用八进制表示,方便记忆。
Close 函数:
#include <unistd.h>
int close(int fd);
返回值:成功返回0,出错返回-1并设置errno
虽然进程终止后,系统会自动清理残余的文件描述符。但是每次打开资源,退出时关闭资源也不失为一个良好的习惯。
#include <stdio.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <fcntl.h>
#include <unistd.h>
int main(){
int fd;
fd = open("./hello.txt", O_CREAT | O_WRONLY);
if(fd > 0){
printf("open file successfully\n And fd = %d\n", fd);
}else{
perror("./hello.txt");
}
close(fd);
return 0;
}
输出:open file successfully
And fd = 3