从linux开始收缩(截断)文件

时间:2011-02-23 22:59:11

标签: file truncate shrink

是否可以在Linux(和/或其他Unix)上“缩小”文件?我想将它用于持久队列(没有适合我需要的现有实现)。从文件的结尾我猜这可能是truncate()。

3 个答案:

答案 0 :(得分:0)

如果您正在使用ext4,xfs或其他现代文件系统,则从Linux Kernel 3.15开始,您可以使用:

#include <fcntl.h>

int fallocate(int fd, int mode, off_t offset, off_t len);

带有FALLOC_FL_COLLAPSE_RANGE标志。

http://manpages.ubuntu.com/manpages/disco/en/man2/fallocate.2.html

答案 1 :(得分:-2)

是的,您可以使用cuttail删除部分文件。

cut -b 17- input_file
tail -c +17 input_file

这将从第17个字节开始输出input_file的内容,从而有效地删除文件的前16个字节。请注意,cut示例还将为输出添加换行符。

答案 2 :(得分:-5)

我使用以下Python脚本截断了64,000 000字节作为参数的文件:

#!/usr/bin/env python

import sys
import os

file = sys.argv[1]
f = os.open(file, os.O_RDWR)
os.ftruncate(f, 64000000)
os.close(f)
相关问题