#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);
文件打开函数:1: open(要打开的文件名,打开方式);
2: open(要打开的文件名,打开方式,mode权限);
flags:O_RDONLY 只读打开
O_WRONLY 只写打开
O_RDWR 可读可写打开
O_CREAT 若文件不存在则创建它
O_EXCL 和 O_CREAT 同时使用,而文件已存在则出错
O_APPEND 每次写入是都加到文件尾部
O_TRUNC 如果文件有内容,则将其内容全部删掉,从新写入
O_APPEND 和 O_TRUNC用法:
假设有文件:file
file 中内容为:you are good
int fd;
char *buf = "hello";
fd=open("./file",O_RDWR);
write(fd,buf,strlen(buf));
运行结果:file 中内容为 hellore good
当以O_APPEND方式打开时,结果为:
you are good
hello
当以O_TRUNC方式打开时,结果为:hello
1.int open(const char *pathname, int flags);
fd = open("./file",O_RDWR);
2.int open(const char *pathname, int flags, mode_t mode);
fd = open("./file",O_RDWR|O_CREAT,0600);
mode:一定实在flags中使用了 O_CREAT,记录待创建文件的权限(0600)。
例如:下面程序中的:
fd = open("./file",O_RDWR|O_CREAT,0600);
当文件不存在打开失败时,需要创建文件,用到或运算符(' | ' )。
#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);
if(fd > 0){
printf("open file succeess\n");
}
}
close(fd);
return 0;
}
open函数返回值为整型。
所以:int fd=open( , );
当文件打开失败返回值为:-1