linux 下open函数的O_APPEND和O_TRUNC标志

1.O_TRUNC标志

使用这个标志,在调用open函数打开文件的时候会将文件原本内容全部丢弃,文件大小变为0;

测试代码

/*
 * @Descripttion: sky
 * @version: 1.0.0
 * @Author: GECHENG
 * @Date: 2021-07-26 22:38:21
 * @note: 
 */
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
#include <stdio.h>
#include <stdlib.h>

int main(void)
{
    int fd;
    // 打开文件
    fd =open("./src_file",O_WRONLY|O_TRUNC);
    if(-1 ==fd)
    {
        perror("sky error");
        exit(-1);
    }
    close(fd);
    exit(0);
}

2.O_APPEND标志

如果open函数带了O_APPEND标志,调用open函数打开文件,当每次使用write()函数对文件进行写操作时,都会把文件当前位置偏移量移动到文件末尾,从文件末尾写入数据。测试代码如下

/*
 * @Descripttion: sky
 * @version: 1.0.0
 * @Author: GECHENG
 * @Date: 2021-07-26 22:38:21
 * @note: 
 */
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int main(void)
{
    char buffer[16];
    int fd;
    int ret;

    fd =open("./src_file",O_RDWR|O_APPEND);
    if(-1 ==fd)
    {
        perror("sky error");
        exit(-1);
    }

    memset(buffer,0x55,sizeof(buffer));

    ret =write(fd,buffer,4);
    if(-1 ==ret)
    {
        perror("write error");
        goto err;
    }

    memset(buffer,0,sizeof(buffer));

    ret=lseek(fd, -4, SEEK_END);
    if(-1 ==ret)
    {
        perror("lseek error");
        goto err;
    }

    ret =read(fd, buffer, 4);
    if(-1 ==ret)
    {
        perror("read error");
        goto err;
    }
    printf("0x%x 0x%x 0x%x 0x%x\n",buffer[0],buffer[1],buffer[2],buffer[3]);
    ret =0;

err:
    close(fd);
    exit(ret);
}

  • 3
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
Linuxopen函数用于打开文件并返回文件描述符。 open函数的语法如下: ```c #include <fcntl.h> int open(const char *pathname, int flags); int open(const char *pathname, int flags, mode_t mode); ``` 其,pathname是文件的路径名,flags是打开文件时的标志,mode是文件的访问权限。 flags参数可以设置为以下值之一或多个值的按位或: - O_RDONLY:只读打开 - O_WRONLY:只写打开 - O_RDWR:读写打开 - O_CREAT:如果文件不存在,则创建文件 - O_TRUNC:如果文件存在且以写方式打开,则截断文件为零长度 - O_APPEND:以追加方式打开文件 mode参数只有在O_CREAT标志被设置时才有效,用于指定文件的访问权限,可以设置为以下值之一: - S_IRUSR:用户可读 - S_IWUSR:用户可写 - S_IXUSR:用户可执行 - S_IRGRP:组可读 - S_IWGRP:组可写 - S_IXGRP:组可执行 - S_IROTH:其他用户可读 - S_IWOTH:其他用户可写 - S_IXOTH:其他用户可执行 例如,如果要以读写方式打开一个文件,可以使用以下代码: ```c #include <fcntl.h> int fd = open("/path/to/file", O_RDWR); if (fd == -1) { // 打开文件失败 } // 在文件进行读写操作 ``` 如果要创建一个新文件并以写方式打开它,可以使用以下代码: ```c #include <fcntl.h> int fd = open("/path/to/new_file", O_WRONLY | O_CREAT, S_IRUSR | S_IWUSR); if (fd == -1) { // 创建文件失败 } // 在新文件进行写操作 ```

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值