unix/linux文件操作函数open的几种flag

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;
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值