如何在Linux (Red Hat Linux)系统中快速创建大文件?

dd可以完成这项工作,但是从/dev/zero读取并写入驱动器可能会花费很长时间,因为您需要一个几百gb大小的文件进行测试……如果你需要重复这样做,时间就会增加。

我不关心文件的内容,我只想快速创建它。如何做到这一点呢?

使用稀疏文件不能解决这个问题。我需要为文件分配磁盘空间。


当前回答

这是一个常见的问题——尤其是在当今的虚拟环境中。不幸的是,答案并不像人们想象的那么简单。

Dd显然是第一选择,但Dd本质上是一个副本,它迫使您写入每个数据块(因此,初始化文件内容)…初始化占用了大量的I/O时间。(想要花更长的时间?使用/dev/random而不是/dev/zero!然后你将使用CPU以及I/O时间!)最后,dd是一个糟糕的选择(尽管它本质上是VM“create”gui使用的默认值)。例句:

dd if=/dev/zero of=./gentoo_root.img bs=4k iflag=fullblock,count_bytes count=10G

truncate is another choice -- and is likely the fastest... But that is because it creates a "sparse file". Essentially, a sparse file is a section of disk that has a lot of the same data, and the underlying filesystem "cheats" by not really storing all of the data, but just "pretending" that it's all there. Thus, when you use truncate to create a 20 GB drive for your VM, the filesystem doesn't actually allocate 20 GB, but it cheats and says that there are 20 GB of zeros there, even though as little as one track on the disk may actually (really) be in use. E.g.:

 truncate -s 10G gentoo_root.img

fallocate是用于虚拟机磁盘分配的最终——也是最好的——选择,因为它本质上是“保留”(或“分配”您正在寻找的所有空间,但它不需要写任何东西。因此,当您使用fallocate创建一个20 GB的虚拟驱动器空间时,您实际上得到了一个20 GB的文件(不是一个“稀疏文件”,并且您不会费心向其写入任何内容—这意味着几乎任何东西都可以在其中—有点像一个全新的磁盘!)例如:

fallocate -l 10G gentoo_root.img

其他回答

来自其他答案的Dd是一个很好的解决方案,但它的速度较慢。在Linux(和其他POSIX系统)中,我们有fallocate,它使用所需的空间,而不必实际写入它,与大多数现代基于磁盘的文件系统一起工作,非常快:

例如:

fallocate -l 10G gentoo_root.img

你也可以使用“yes”命令。语法相当简单:

#yes >> myfile

按“Ctrl + C”停止它,否则它将耗尽所有可用空间。

要清除该文件,请执行以下命令:

#>myfile

将清除此文件。

其中seek是你想要的文件的大小,单位是字节- 1。

dd if=/dev/zero of=filename bs=1 count=1 seek=1048575

我不认为你会比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。