基础 IO - O_TRUNC 详解

一、效果

若文件已存在且为普通文件,并且允许写入(即参数 flags 包含 O_RDWR 或O_WRONLY),则该文件长度会被截断为 0

注意

O_RDONLY | O_TRUNC 是未定义的,测试 Linux(3.10.0-1160.el7.x86_64) 会被截断

二、实操验证

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#include <unistd.h>
#include <fcntl.h>
#include <string.h>

int main()
{
  const char *filename = "test.txt";
  const char *content = "O_TRUNC\n";
  int         fd, len;

  fd = open(filename, O_WRONLY | O_CREAT | O_TRUNC, 0644);
  if (fd == -1)
  {
    perror("open");
    return EXIT_FAILURE;
  }

  len = strlen(content);

  if (len != write(fd, content, len))
  {
    perror("write");
    return EXIT_FAILURE;
  }

  close(fd);

  return EXIT_SUCCESS;
}
$ cat test.txt
aaaaaaaaaaaaaaaa
$ ./O_TRUNC_test
$ cat test.txt
O_TRUNC
$

测试 Linux(3.10.0-1160.el7.x86_64) 会被截断

注意

一般不会使用 O_RDONLY | O_TRUNC 去操作文件,如下测试只是为了拓展

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#include <unistd.h>
#include <fcntl.h>
#include <string.h>

int main()
{
  const char *filename = "test.txt";
  int         fd;

  fd = open(filename, O_RDONLY | O_TRUNC);
  if (fd == -1)
  {
    perror("open");
    return EXIT_FAILURE;
  }

  close(fd);

  return EXIT_SUCCESS;
}
$ uname -a
Linux test 3.10.0-1160.el7.x86_64 #1 SMP Mon Oct 19 16:18:59 UTC 2020 x86_64 x86_64 x86_64 GNU/Linux
$ cat test.txt
O_TRUNC
$ ./a.out
$ ll test.txt
-rw-rw-r-- 1 mam mam 0 9月  22 11:36 test.txt
$
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值