SYNOPSIS
#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);
in creat(const char *pathname,mode_t mode);
DESCRIPTION
Given a pathname for a file,open() returns a file descriptor,a small,nonnegative interger for use in subsequent system calls (read(2),write(2),lseek(2),fcntl(2),etc.). The file descriptor returned by a successful call will be the lowest-numbered file descriptor not currently open for the process
参数说明
int open(const char *pathname,int flags);
int open(const char *pathname,int flags,mode_t_ mode);
**Pathname **:要打开的文件名(含路径,缺省为当前路径)
Flags:
O_RDONLY 只读打开
O_WRDONLY 只写打开
O_RDWR 可读可写打开
当我们附带了权限后,打开的文件就只能按照这种权限来操作。
以上这三个常数中应当只指定一个。下列常数是可选择的:
O_CREAT 若文件不存在则创建它。使用此选项时,需要同时说明第三个参数mode.用其说明该文件的存取许可权限。
O_EXCL 如果同时指定了O_CREAT,而文件已经存在,则出错。
O_APPEND 每次读写时都加到文件的尾端。
O_TRUNC 属性去打开文件时,如果这个文件中本来就是有内容的,而且为只读或只写成功打开,则将其长度截短为0
Mode:一定是在flags中使用了O_CREAT 标志,mode记录待创建的文件的访问权限
$touch file1
$vi demo1.c
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include<stdio.h>
int main(){
// file description
int fd;
fd= open("./file1",O_RDWR);
printf("fd=%d\n",fd);
return 0;
}
$gcc demo1.c
$./a.out
$fd=3
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include<stdio.h>
int main(){
// file description
int fd;
fd= open("./file1",O_RDWR);
if(fd==-1){
printf("open file1 fail\n");
fd = open("./file1",O_RDWR|O_CREAT,0600);
if(fd>0){
printf("create file1 success\n");
}
}
return 0;
}
~
解读:0 6(4+2) 0 同组 0 其他组
1.可读权限 :r 4
2.可写权限:w 2
3.执行权限:x 1