Linux系统编程——文件打开创建的补充

int open(const char *pathname, int flags);
int open(const char *pathname, int flags, mode_t mode);

O_RDONLY只读打开        O_WRONLY只写打开        O_RDWR可读可写打开

当我们附带了权限后,打开的文件就只能按照这种权限来操作。

以上三个常数中只能选择一个。下列常数是可选择的。

O_CREAT若文件不存在则创建它。使用此选项时,需要说明第三个参数mode,用其说明该文件的存取许可权限。

O_EXCL如果同时指定了O_CREAT,而文件已经存在,则出错。

O_APPEND每次写时都加到文件的尾端

O_TRUNC属性去打开文件时,如果这个文件本来是有内容的,而且只读或只写成功打开,则其长短截断为0.

mode:一定是flags中使用了O_CREAT标志,mode记录待创建的文件的访问权限

文件file1原始内容:

O_EXCL代码示例:

#include <stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>

int main()
{
        int fd;
        fd = open("./file1",O_RDWR|O_CREAT|O_EXCL,0600);
        if(fd = -1){
                printf("file1 already exists\n");
        }
        close(fd);
        return 0;
}

O_APPEND代码示例:

#include <stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
#include <stdlib.h>
#include <string.h>

int main()
{
        int fd;
        int n_write;
        char readBuf[128] = {'\0'};
        char *buf = "Practice and review";
        fd = open("./file1",O_RDWR|O_CREAT|O_APPEND,0600);
        if(fd > 0){
                printf("open file1 success fd = %d\n",fd);
        }
        n_write = write(fd,buf,strlen(buf));
        printf("write %d byte\n",n_write);
        close(fd);
        return 0;
}

O_TRUNC代码示例:

#include <stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
#include <stdlib.h>
#include <string.h>

int main()
{
        int fd;
        int n_write;
        char readBuf[128] = {'\0'};
        char *buf = "Practice and review";
        fd = open("./file1",O_RDWR|O_CREAT|O_TRUNC,0600);
        if(fd > 0){
                printf("open file1 success fd = %d\n",fd);
        }
        n_write = write(fd,buf,strlen(buf));
        printf("write %d byte\n",n_write);
        close(fd);
        return 0;
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

牵猫散步的鱼儿

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值