函数:open
在终端输入命令
man 2 open
跳转以下页面
要使用这个API就要包含这些头文件 ,在终端都会有显示。
#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);
int creat(const char *pathname, mode_t mode);
//pathname:要打开的文件名(含路径,缺省为文件名);
//flags:
O_RDONLY 只读打开 O_WRONLY 只写打开 O_RDWR可读可写打开
Mode:一定是在flags中使用了O_CREAT标志,mode记录创建文件访问权限。
我们先编程体验下这个函数,在当前路径下创建一个文件,暂且叫file1;之后写代码如下:
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <stdio.h>
int main()
{
int fd;
fd = open("./file1",O_RDWR);//file1是我们新创建的文件
printf("fd = %d \n",fd);
return 0;
}
打开成功返回的值是3,如果我们删掉file1这个文件,那么返回值是-1;或者把file1改成一个不存在的文件,返回值也是-1;
我们在体验下带3个参数的open函数,第3个参数是权限;
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <stdio.h>
int main()
{
int fd;
fd = open("./file1",O_RDWR);
if(fd == -1)
{
printf("open file1 failed\n");
fd = open("./file1",O_RDWR|O_CREAT,0600);//0600的权限是可读可写
if(fd > 0 )
{
printf("creat file1 success !\n");
}
}
printf("fd = %d \n",fd);
1,1 顶端
return 0;
}