open函数
原型:
#include <stdio.h>
#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);
Open : 打开文件成功 返回值为一个大于0的整型数 打开文件失败 返回值为 -1
各参数详解:
- pathname: 要打开的文件名(含路径,缺省为当前路径)
- flags:
O_RDONLY
只读打开O_WRONLY
只写打开O_RDWR
可读可写打开
当我们附带了权限后,打开的文件就只能按照这种权限来操作。
以上者三个常数中应当只指定一个。下列常数是可选择的:
O_CREAT
若文件不存在则创建它。使用此选项时,需要同时说明第三个参数mode,用其说明该新文件的存取许可权限。
O_EXCL
如果同时指定了O_CREAT,而文件已经存在,则出错。
#include <stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
int main()
{
int fd;
umask(0000);
fd = open("./file1",O_RDWR|O_CREAT|O_EXCL,0777);
if(fd == -1)
{
printf("file had created\n");
}else
{
printf("file open sucsses fd = %d\n",fd^;
}
return 0;
}
fd — 文件描述符,打开文件成功返回一个大于0的正数,打开失败返回-1
O_APPEND
每次写时都加到文件的尾端。
fd = open("./file1",O_RDWR|O_APPEND);
O_TRUNC
属于去打开文件时,如果这个文件中本来是有内容的,而且为只读或只写成功打开,则将其长度截短为0
- Mode : 一定是在flags中使用了 O_CREAT标志,mode记录用来待创建的文件的访问权限
首先了解一下 umask 命令,该命令用来设置限制新文件权限的掩码。当新文件被创建时,其最初的权限由文件创建掩码决定。简单地来说,umask和open()及creat()函数的权限码(mode_t mode参数)共同决定你的新建文件的权限。具体关系为mode & ~umask。
umask(0000);
fd = open("./file1",O_RDWR|O_CREAT|O_EXCL,0777);
这样就是设置文件file1的权限为 0777&(~0000) = 0777
即为- rwx rwx rwx
可读可写可执行