如何在不读取整个文件的情况下从大文件的末尾删除X字节?

在Linux中,我有一个很大的文件,文件末尾附加了一些无关的信息。例如,假设我知道一个1.6GB文件的末尾有314个字节的无关数据。

当然,将更多数据添加到文件末尾是非常容易和有效的,但是我可以怎么做才能删除它,而不必将该文件的第一部分复制到另一个文件中(或覆盖所述文件)?

我在C中看到了一些很好的建议。我希望从命令行编写脚本,但是如果没有,我会比C更倾向于在python中进行编写。

我看到python在其文件对象上有一个truncate方法,但是无论我如何使用它似乎都在破坏我的文件-我应该能够弄清楚这一点,但是当然答案仍然值得欢迎。

回答:

使用功能 truncate

http://linux.die.net/man/2/truncate

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

int ftruncate(int fd, off_t length);

truncate采用文件名

ftruncate采用打开的文件描述符

两者都将文件长度设置为,length因此它会被截断或拉长(在后一种情况下,文件的其余部分将填充为NULL / ZERO)。

truncate(Linux shell命令)也将起作用

**SYNTAX**

truncate -s integer <filename>

**OPTIONS**

-s number specify the new file length. If the new length is smaller than the current filelength data is lost. If the new length is greater the file is padded with 0. You can specify a magnitude character to ease large numbers:

b or B size is bytes.

k size is 1000 bytes.

K size is 1024 bytes.

m size is 10^6 bytes.

M size is 1024^2 bytes.

g size is 10^9 bytes.

G size is 1024^3 bytes.

**EXAMPLES**

To shrink a file to 10 bytes:

truncate -s 10 /tmp/foo

To enlarge or shrink a file to 345 Megabytes:

truncate -s 345M /tmp/foo

以上是 如何在不读取整个文件的情况下从大文件的末尾删除X字节? 的全部内容, 来源链接: utcz.com/qa/403976.html

回到顶部