一、效果
若文件已存在且为普通文件,并且允许写入(即参数 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
$
1284

被折叠的 条评论
为什么被折叠?



