linux系统编程下的open函数使用方法
open函数属于Linux中系统IO,用于“打开”文件,代码打开一个文件意味着获得了这个文件的访问句柄。int fd = open(参数1,参数2,参数3);int fd = open(const char *pathname,int flags,mode_t mode);1.句柄(file descriptor 简称fd)首先每个文件都属于自己的句柄,例如标准输入是0,标准输出是1,标准出错是2
目录
open函数属于Linux中系统IO,用于“打开”文件,代码打开一个文件意味着获得了这个文件的访问句柄。
int fd = open(参数1,参数2,参数3);
int fd = open(const char *pathname,int flags,mode_t mode);
1.句柄(file descriptor 简称fd)
首先每个文件都属于自己的句柄,例如标准输入是0,标准输出是1,标准出错是2。
每打开一个文件就会返回句柄来操作这个文件,一般是从3开始,然后4,5,6一直下去。
close(fd)之后句柄就返回给系统,例如打开一个文件后fd是3,close之后再打开另外一个文件也还是3,但代表的文件不一样了。
2.使用open前需要先包含头文件
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
3.参数说明
int fd = open(const char *pathname,int flags,mode_t mode);
3.1 参数1(pathname)
即将要打开的文件路径,例如:“a.txt”当前目录下的a.txt文件
3.2 参数2(flags)
flags分为两类:主类,副类
主类:
O_RDONLY 以只读方式打开
O_WRONLY 以只写方式打开
O_RDWR 以可读可写方式打开
这三种方式是互斥的。
副类:
O_CREAT 如果文件不存在则创建该文件
O_EXCL 如果使用O_CREAT选项且文件存在,则返回错误消息
O_NOCTTY 如果文件为终端,那么终端不可以调用open系统调用的那个进程的控制终端
O_TRUNC 如果文件已经存在则删除文件中原有数据
O_APPEND 以追加的方式打开
主副可以配合使用,例如:O_RDWR|O_CREAT|O_TRUNC
3.3 参数3(mode)
mode:如果文件被新建,指定其权限未mode。
mode是八进制权限码,0777表示文件所有者。该文件用户组,其他用户都有可读可写可执行权限。
4. 用法示例
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
#include <stdlib.h>
#include <stdio.h>
int main()
{
int fd;
//创建新文件
fd=open("myhello",O_RDWR | O_CREAT,0777);
if(fd == -1)
{
perror("open file");
exit(1);
}
printf("fd = %d\n",fd);
int ret = close(fd);
printf("ret = %d\n",ret);
if(ret == -1)
{
perror("close file");
exit(1);
}
}
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
#include <stdlib.h>
#include <stdio.h>
int main()
{
int fd;
//创建新文件判断是否存在
fd=open("myhello",O_RDWR | O_CREAT | O_EXCL,0777);
if(fd == -1)
{
perror("open file");
exit(1);
}
printf("fd = %d\n",fd);
int ret = close(fd);
printf("ret = %d\n",ret);
if(ret == -1)
{
perror("close file");
exit(1);
}
}
原文链接:https://blog.csdn.net/weixin_39296438/article/details/79422068
更多推荐
所有评论(0)