Sun*_*Wei 19
回答,现在这是Linux内核v3.15(ext4/xfs)的现实
请阅读 http://man7.org/linux/man-pages/man2/fallocate.2.html
测试代码
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <stdlib.h>
#include <fcntl.h>
#ifndef FALLOC_FL_COLLAPSE_RANGE
#define FALLOC_FL_COLLAPSE_RANGE 0x08
#endif
int main(int argc, const char * argv[])
{
int ret;
char * page = malloc(4096);
int fd = open("test.txt", O_CREAT | O_TRUNC | O_RDWR, 0644);
if (fd == -1) {
free(page);
return (-1);
}
// Page A
printf("Write page A\n");
memset(page, 'A', 4096);
write(fd, page, 4096);
// Page B
printf("Write page B\n");
memset(page, 'B', 4096);
write(fd, page, 4096);
// Remove page A
ret = fallocate(fd, FALLOC_FL_COLLAPSE_RANGE, 0, 4096);
printf("Page A should be removed, ret = %d\n", ret);
close(fd);
free(page);
return (0);
}
Run Code Online (Sandbox Code Playgroud)
大多数文件系统都无法删除文件的开头,并且没有通用API可以执行此操作; 例如,truncate函数仅修改文件的结尾.
您可以使用某些文件系统来执行此操作.例如,ext4文件系统最近得到了一个你可能会觉得有用的ioctl:http://lwn.net/Articles/556136/
更新:编写此答案大约一年后fallocate,通过该FALLOC_FL_COLLAPSE_RANGE模式将支持从ext4和xfs文件系统上的文件的开头和中间删除块的操作添加到该函数中.它比自己使用低级别的iotcl更方便.
还有一个与C函数同名的命令行实用程序.假设您的文件位于受支持的文件系统上,这将删除前100MB:
fallocate -c -o 0 -l 100MB yourfile
Run Code Online (Sandbox Code Playgroud)
如果您可以使用 ASCII 行而不是字节,那么删除文件的前 n 行就很容易。例如删除前 100 行:
sed -i 1,100d /path/to/file
Run Code Online (Sandbox Code Playgroud)
请阅读一本好的Linux编程书籍,例如Advanced LinuxProgramming。
您需要使用Linux 内核系统 调用,请参阅syscalls(2)
特别是truncate(2)(既用于截断,又用于在支持它的文件系统上扩展稀疏文件),以及stat(2)来获取文件大小。
没有(可移植的或文件系统中立的)方法可以从文件的开头(或中间)删除字节,您只能在文件的末尾截断文件。