【问题标题】:PHP file size is unchanged after appending追加后PHP文件大小不变
【发布时间】:2011-11-07 13:39:34
【问题描述】:

我遇到了 PHP 文件 I/O 的问题。

$file = fopen("/tmp/test.txt", "w");
fwrite($file,"hi there\n");
fclose($file);
echo filesize("/tmp/test.txt")."\n"; # displays 9

$file = fopen("/tmp/test.txt", "a");
fwrite($file,"hi there\n");
fclose($file);
echo filesize("/tmp/test.txt")."\n"; # also displays 9 !!!!!!!

正如大家所见,我在初始写入后通过附加来更改文件大小。为什么在这两种情况下我都得到 9 作为文件大小?我期望 18 作为案例 2 的输出。

【问题讨论】:

  • 这个脚本执行后文件的内容是什么?
  • 亲爱的 hsz 它有预期的内容。它有 18 个字符。

标签: php caching file-io filesize


【解决方案1】:

您需要通过调用函数clearstatcache清除文件状态缓存之前修改文件后再次调用filesize()

// write into file.
// call filesize()

clearstatcache();

// append to the fiile.
// call filesize()

为了获得更好的性能,PHP 会缓存 filesize() 的结果,因此您需要告诉 PHP 在对修改的文件再次调用 filesize() 之前清除该缓存。

【讨论】:

  • 太棒了!!像魅力一样工作。
猜你喜欢
  • 2015-09-21
  • 2014-07-06
  • 1970-01-01
  • 1970-01-01
  • 2014-05-21
  • 2017-08-12
  • 2021-01-08
  • 2011-09-27
  • 2012-12-28
相关资源
最近更新 更多