以下问题:How to quickly create large files in C?
我记得4-5年前,我能够在Linux中使用fallocate
shell实用程序创建没有漏洞/空白的文件。
磁盘文件系统是ext3,ext4或xfs。
当时,fallocate
Shell实用程序在不到一秒钟的时间内创建了8 GB的文件。我不记得文件是否充满零或随机。
我现在尝试复制此文件,但似乎创建的文件带有漏洞/空白。
我想知道这是用C
语言完成的吗?
Linux上的fallocate
系统调用具有将空间归零的选项。
fallocate
注意,并非所有文件系统都支持#define _GNU_SOURCE
#include <fcntl.h>
#include <stdio.h>
#include <stdlib.h>
int main(void)
{
int fd = open("testfile", O_RDWR | O_TRUNC | O_CREAT, 0755);
off_t size = 1024 * 1024 * 1024;
if (fd == -1) {
perror("open");
exit(1);
}
if (fallocate(fd, FALLOC_FL_ZERO_RANGE, 0, size) == -1) {
perror("fallocate");
exit(1);
}
}
。 FALLOC_FL_ZERO_RANGE
支持它。
否则,如果您正在寻找更便携式的解决方案(当然效率不高),则可以自己编写零。