我如何在 PHP 中创建给定大小的文件(无论内容如何)?

我必须创建一个大于 1GB 的文件。最大约 4-10GB

有帮助吗?

解决方案

您可以利用 fopenfseek

define('SIZE',100); // size of the file to be created.
$fp = fopen('somefile.txt', 'w'); // open in write mode.
fseek($fp, SIZE-1,SEEK_CUR); // seek to SIZE-1
fwrite($fp,'a'); // write a dummy char at SIZE position
fclose($fp); // close the file.

执行时:

$ php a.php

$ wc somefile.txt
  0   1 100 somefile.txt
$ 

其他提示

如果该文件的内容是不相关的,然后只是填充它 - 但是,请确保你不会产生变化的过大的内存来保存:

<?php
$fh = fopen("somefile", 'w');
$size = 1024 * 1024 * 10; // 10mb
$chunk = 1024;
while ($size > 0) {
   fputs($fh, str_pad('', min($chunk,$size)));
   $size -= $chunk;
}
fclose($fh);

如果该文件必须由别的东西可读 - 你再怎么做取决于其需要读它的另一件事

下进行。

在底部看我的代码

^^的最大特点是在这里以0来创建4GB的文件^^

FUNCTION CreatFileDummy($file_name,$size) {   
// 32bits 4 294 967 296 bytes MAX Size
    $f = fopen($file_name, 'wb');
    if($size >= 1000000000)  {
        $z = ($size / 1000000000);       
        if (is_float($z))  {
            $z = round($z,0);
            fseek($f, ( $size - ($z * 1000000000) -1 ), SEEK_END);
            fwrite($f, "\0");
        }       
        while(--$z > -1) {
            fseek($f, 999999999, SEEK_END);
            fwrite($f, "\0");
        }
    }
    else {
        fseek($f, $size - 1, SEEK_END);
        fwrite($f, "\0");
    }
    fclose($f);

Return true;
}

测试^^ Max在腓32bit的4 294 967 296:

CreatFileDummy( 'mydummyfile.iso',4294967296);

您想要写,读和科瑞文件虚拟我的代码是在这里^^:

https://github.com/Darksynx/php

算法产生大的虚拟文件

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top