Linux文件创建——open/creat函数,功能O_RDWR|O_CREAT|O_EXCL|O_APPEND|O_TRUNC

在这里插入图片描述

O_CREAT 函数已经用过了,若不存在就新建一个文件
我们来看看 O_EXAL 函数吧(若文件存在,则返回-1
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
#include<stdlib.h>
#include<fcntl.h>
#include<stdio.h>

int main()
{
    
    
        int fd;
        fd=open("./qqq.c",O_RDWR|O_CREAT|O_EXCL,0600);
        if(fd==-1)
        {
    
    
                printf("file exist!\n");
        }
        else
        {
    
    
                printf("creat file!\n");
        }
        close(fd);
        return 0;
}



在这里插入图片描述
成功了!

接下来看看 O_APPEND 函数

我们现在qqq.c这个文件中随便写一些东西
在这里插入图片描述

然后运行下面这个代码

#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
#include<stdlib.h>
#include<fcntl.h>
#include<stdio.h>
int main()
{
    
    
        int fd;
        char *buf="LLP IS MY WIEF!";
        fd=open("./qqq.c",O_RDWR);
        printf("fd=%d\n",fd);
        int n_write=write(fd,buf,strlen(buf));
        if(n_write!=-1)
        {
    
    
                printf("write %d byte to file\n",n_write);
        }

        close(fd);
        return 0;
}


再打开qqq.c这个文件

在这里插入图片描述
会发现后面写的数据把之前的覆盖掉了。
然后我们加上O_APPEND

#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
#include<stdlib.h>
#include<fcntl.h>
#include<stdio.h>
int main()
{
    
    
        int fd;
        char *buf="LLP IS MY WIEF!";
        fd=open("./qqq.c",O_RDWR|O_APPEND);
        printf("fd=%d\n",fd);
        int n_write=write(fd,buf,strlen(buf));
        if(n_write!=-1)
        {
    
    
                printf("write %d byte to file\n",n_write);
        }

        close(fd);
        return 0;
}


在这里插入图片描述
就没有覆盖,而是紧接着之前的数据写入

接下来我们看看 O_TRUNC 函数

如果之前文件里面有内容,先把内容清零,然后写入新的。
假如还是刚才那个文件qqq.c里面有内容了,接下来运行这个代码

#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
#include<stdlib.h>
#include<fcntl.h>
#include<stdio.h>
#include<string.h>
int main()
{
    
    
        int fd;
        char *buf="FOREVER!";
        fd=open("./qqq.c",O_RDWR|O_TRUNC);
        printf("fd=%d\n",fd);
        int n_write=write(fd,buf,strlen(buf));
        if(n_write!=-1)
        {
    
    
                printf("write %d byte to file\n",n_write);
        }

        close(fd);
        return 0;
}


运行结果为:
在这里插入图片描述

可见,之前的数据都没了

接下来还有一个create函数

#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
#include<stdlib.h>
#include<fcntl.h>
#include<stdio.h>
#include<string.h>
int main()
{
    
    
        int fd;
        fd=creat("/home/CLC/QYY/file01",S_IRWXU);

        close(fd);
        return 0;
}

在这里插入图片描述
create函数里面第一项是填需要创建文件的详细位置。

猜你喜欢

转载自blog.csdn.net/qq_43482790/article/details/115049765
o
今日推荐