int open(const char *pathname, int flags, mode_t mode)
pathname:文件名(文件路径)
mode:使用权限(同Linux文件权限相似4-r,w-2,x-1)
flags:以某种模式打开文件
flags具体参数:
O_RDONLY :只读权限
O_WRONLY:只写权限
O_RDWR:读写权限
O_CREAT:若文件不存在将创建一个新文件
O_EXCL:通过 O_CREAT, 生成 文件,若文件已经 存在,则open出错,调用失败
O_TRUNC:文件已经存在,且是一个普通文件 ,打开 模式又是 可写 , 清空文件内容(清空原 有内容,重写)
O_APPEND:文件以追加模式打开,在写以前 ,文件读写指针被置在文件的末尾(追加模文件内容)
返回值
open函数执行成功返回一个新的文件描述符 (若是有错误 发生返回-1,并在errno设置错误信息)
demo1:
1.创建file文件
2.修改文件权限
3.测试O_EXCL
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <stdio.h>
#include <stdlib.h>
void result()
{
umask(0);
int fd;
fd = open("/root/pro/file",O_CREAT|O_EXCL,0777);
if(fd == -1)
{
printf("file exist\n");
}
close(fd);
}
int main()
{
result();
return 0;
}
结果演示
demo2:
1.创建文件(文件内容:hello)
2.修改文件权限
3.测试O_APPEND(原有文件内容后面追加word)
4.测试O_TRUNC(依据上步,修改文件内容为hello)
结果演示
#include <stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <stdlib.h>
#include <string.h>
void result()
{
int fd;
int fd_write;
char *write_buf = "word\n";
fd = open("/root/pro/file",O_APPEND|O_RDWR,0777);
if(fd == -1)
{
printf("open file fail\n");
perror("why");
exit(-1);
}
fd_write = write(fd,write_buf,strlen(write_buf));
if(fd_write == -1)
{
printf("write file fail\n");
perror("why");
exit(-1);
}
close(fd);
}
int main()
{
result();
return 0;
}
#include <stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <stdlib.h>
#include <string.h>
void result()
{
int fd;
int fd_write;
char *write_buf = "hello\n";
fd = open("/root/pro/file",O_TRUNC|O_RDWR,0777);
if(fd == -1)
{
printf("open file fail\n");
perror("why");
exit(-1);
}
fd_write = write(fd,write_buf,strlen(write_buf));
if(fd_write == -1)
{
printf("write file fail\n");
perror("why");
exit(-1);
}
close(fd);
}
int main()
{
result();
return 0;
}