首頁  >  問答  >  主體

建立指定大小的php文件

如何在 PHP 中建立給定大小的檔案(無論內容為何)?

我必須建立一個大於 1GB 的檔案。最大約 4-10GB

P粉221046425P粉221046425333 天前548

全部回覆(2)我來回復

  • P粉561323975

    P粉5613239752023-10-27 11:36:14

    如果檔案的內容不相關,則只需填充它 - 但請確保不會產生太大而無法保存在記憶體中的變數:

    <?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);

    如果檔案必須被其他東西讀取 - 那麼你如何做到這一點取決於需要讀取它的其他東西。

    C.

    回覆
    0
  • P粉039633152

    P粉0396331522023-10-27 09:16:19

    您可以使用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
    $

    回覆
    0
  • 取消回覆