如何在Linux (Red Hat Linux)系统中快速创建大文件?
dd可以完成这项工作,但是从/dev/zero读取并写入驱动器可能会花费很长时间,因为您需要一个几百gb大小的文件进行测试……如果你需要重复这样做,时间就会增加。
我不关心文件的内容,我只想快速创建它。如何做到这一点呢?
使用稀疏文件不能解决这个问题。我需要为文件分配磁盘空间。
如何在Linux (Red Hat Linux)系统中快速创建大文件?
dd可以完成这项工作,但是从/dev/zero读取并写入驱动器可能会花费很长时间,因为您需要一个几百gb大小的文件进行测试……如果你需要重复这样做,时间就会增加。
我不关心文件的内容,我只想快速创建它。如何做到这一点呢?
使用稀疏文件不能解决这个问题。我需要为文件分配磁盘空间。
当前回答
我不认为你会比dd快很多,瓶颈是磁盘;无论你怎么做,写入几百GB的数据都将花费很长时间。
But here's a possibility that might work for your application. If you don't care about the contents of the file, how about creating a "virtual" file whose contents are the dynamic output of a program? Instead of open()ing the file, use popen() to open a pipe to an external program. The external program generates data whenever it's needed. Once the pipe is open, it acts just like a regular file in that the program that opened the pipe can fseek(), rewind(), etc. You'll need to use pclose() instead of close() when you're done with the pipe.
如果你的应用程序需要文件有一定的大小,它将由外部程序来跟踪它在“文件”中的位置,并在到达“结束”时发送一个eof。
其他回答
来自其他答案的Dd是一个很好的解决方案,但它的速度较慢。在Linux(和其他POSIX系统)中,我们有fallocate,它使用所需的空间,而不必实际写入它,与大多数现代基于磁盘的文件系统一起工作,非常快:
例如:
fallocate -l 10G gentoo_root.img
我对Linux不太了解,但这是我多年前在DC共享上编写的伪造大文件的C代码。
#include < stdio.h >
#include < stdlib.h >
int main() {
int i;
FILE *fp;
fp=fopen("bigfakefile.txt","w");
for(i=0;i<(1024*1024);i++) {
fseek(fp,(1024*1024),SEEK_CUR);
fprintf(fp,"C");
}
}
GPL mkfile只是dd的一个(ba)sh脚本包装器;BSD的mkfile只是memsets一个非零的缓冲区,并重复写入它。我不期望前者的性能优于dd。后者可能略微优于dd if=/dev/zero,因为它省略了读取操作,但任何性能明显更好的可能只是创建一个稀疏文件。
如果没有一个系统调用实际为文件分配空间而不写入数据(Linux和BSD缺乏这个,可能Solaris也是如此),您可能会通过使用ftrunc(2)/truncate(1)将文件扩展到所需的大小,将文件mmap到内存中,然后将非零数据写入每个磁盘块的第一个字节(使用fgetconf查找磁盘块大小)来获得性能上的小幅改进。
我不认为你会比dd快很多,瓶颈是磁盘;无论你怎么做,写入几百GB的数据都将花费很长时间。
But here's a possibility that might work for your application. If you don't care about the contents of the file, how about creating a "virtual" file whose contents are the dynamic output of a program? Instead of open()ing the file, use popen() to open a pipe to an external program. The external program generates data whenever it's needed. Once the pipe is open, it acts just like a regular file in that the program that opened the pipe can fseek(), rewind(), etc. You'll need to use pclose() instead of close() when you're done with the pipe.
如果你的应用程序需要文件有一定的大小,它将由外部程序来跟踪它在“文件”中的位置,并在到达“结束”时发送一个eof。
不义之词:OTFFS提供了一个文件系统,可以提供任意大的文件系统。Exabytes是当前的限制)文件生成的内容。它只支持linux,使用纯C语言,并且处于早期alpha版本。
见https://github.com/s5k6/otffs。