创建指定大小的php文件
P粉221046425
P粉221046425 2023-10-26 14:03:01
[PHP讨论组]

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

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

P粉221046425
P粉221046425

全部回复(2)
P粉561323975

如果文件的内容不相关,则只需填充它 - 但请确保不会生成太大而无法保存在内存中的变量:

<?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.

P粉039633152

您可以使用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
$
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责申明 意见反馈 讲师合作 广告合作 最新更新 English
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送
PHP中文网APP
随时随地碎片化学习
PHP中文网抖音号
发现有趣的

Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号