头文件:
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
open函数
- int open(const char *pathname, int flags);
- int open(const char *pathname, int flags, mode_t mode);
pathname:要打开的文件名(含路径,缺省为当前路径)
flags:
O_RDONLY 只读打开
O_WRONLY 只写打开
O_RDWR 可读可写打开
O_CREAT 若文件不存在则创建它(需说明第三个参数mode)
O_EXCL 和O_CREAT 同时使用,而文件已存在则出错
O_APPEND 每次写时都加到文件的尾端
O_TRUNC 属性去打开文件时,如果文件本来有内容,而且为只读或只写成功打开,则将其长度截短为0
mode:一定是在flags中使用了O_CREAT标志,mode记录待创建的文件的访问权限。
open会返回文件描述符,当打开多个文件时,可以通过文件描述符对不同的文件进行区分。(文件打开失败返回-1)
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <stdio.h>
int main()
{
int fd;
fd = open("./file",O_RDWR);
if(fd == -1){
printf("open file failed\n");
fd = open("./file",O_RDWR|O_CREAT,0600); //6=4+2
if(fd > 0)
{
printf("open file success\n");
}
}
return 0;
}
权限:
1.可读 r 4
2.可写 w 2
3.执行 x 1