追加后,PHP文件大小不变


PHP file size is unchanged after appending

我遇到一个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 ?

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

// write into file.
// call filesize()
clearstatcache();
// append to the fiile.
// call filesize()

为了获得更好的性能,PHP缓存filesize()的结果,所以你需要告诉PHP在你再次调用filesize()修改文件之前清除缓存