扫码关注官方订阅号
如何在 PHP 中创建给定大小的文件(无论内容如何)?
我必须创建一个大于 1GB 的文件。最大大约 4-10GB
如果文件的内容不相关,则只需填充它 - 但请确保不会生成太大而无法保存在内存中的变量:
<?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.
您可以使用fopen 和fseek
fopen
fseek
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中文网服务号
QQ扫码加入技术交流群
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号
PHP学习
技术支持
返回顶部
如果文件的内容不相关,则只需填充它 - 但请确保不会生成太大而无法保存在内存中的变量:
<?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.
您可以使用
fopen和fseekdefine('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.执行时: