Linux 文件截断的几种方式

文件截断, 指的是将文件内容分成两半, 只保留需要的文件长度的那部分. 通常, 将文件长度截断为0.
文件截断方式:
1. 使用系统调用open/fopen O_TRUNC截断
open截断文件, 会清空文件已有内容, 即保留长度为0. 指定O_TRUNC标识时, 文件必须可写方式(如O_RDWR, O_WRONLY)打开.

例子,

int fd = open(FILE_PATH, O_RDWR | O_TRUNC); 

close(fd);

注意: 如果fd指向FIFO文件, 或终端设备文件, O_TRUNC标识将会忽略

类似地, 可以使用C库函数fopen截断文件, 功能类似于open, 接口形式不一样
例子,

// "w" <=> O_WRONLY | O_CREAT | O_TRUNC
// "w+" <=> O_RDWR | O_CREAT | O_TRUNC
FILE* fp = fopen(FILE_PATH, "w"); // "w+" 也可以

fclose(fp);

2. 使用系统调用truncate/ftruncate
truncate可以将文件截断为指定长度(byte).
同样可以使用ftruncate, 区别是参数类型, truncate接受字符串形式文件路径, ftruncate接受已打开的文件描述符作为文件路径.

#include <unistd.h>
#include <sys/types.h>

int truncate(const char *path, off_t length);
int ftruncate(int fd, off_t length);

例子,

int ret = truncate(FILE_PATH, 0); // 文件长度截断为0
ret = truncate(FILE_PATH2, 100); // 文件长度截断为100byte

3. 使用shell命令truncate
-s 选项是截断为指定byte长度

$ vim testfile
abcd
$ truncate ./testfile -s 2
$ cat testfile
ab
posted @ 2021-05-23 00:31  明明1109  阅读(4672)  评论(0编辑  收藏  举报