filesize() : giving incorrect result

…衆ロ難τιáo~ 提交于 2019-12-24 12:49:13

问题


I am testing out a tool for modifying files and one fairly important ability during this is telling the file size, especially while the file is still open.

$file = tempnam('/tmp', 'test_');
file_put_contents($file, 'hello world');

echo 'Initial Read: ' . file_get_contents($file).PHP_EOL;

echo 'Initial Size: ' . filesize($file).PHP_EOL;

$fp = fopen($file, 'a');
fwrite($fp, ' then bye');

echo 'Final Read:   ' . file_get_contents($file).PHP_EOL;

fclose($fp);
echo 'Final Size:   ' . filesize($file).PHP_EOL;

This simple script is giving some strange results:

Initial Read: hello world
Initial Size: 11
Final Read:   hello world then bye
Final Size:   11

I thought the final size would have been the result of the file still being open which is why I added the fclose($fp);, however this made no difference. Either way I need to be able to determine the size while the file is still open.

The final size should be 20. Does anyone know the possible cause of this and how to work around it?


回答1:


As this comment is stating, you need to call clearstatcache() before calling filesize() again.

$file = tempnam('/tmp', 'test_');
file_put_contents($file, 'hello world');

echo 'Initial Read: ' . file_get_contents($file).PHP_EOL;

echo 'Initial Size: ' . filesize($file).PHP_EOL;

$fp = fopen($file, 'a');
fwrite($fp, ' then bye');

echo 'Final Read:   ' . file_get_contents($file).PHP_EOL;

fclose($fp);
clearstatcache();

echo 'Final Size:   ' . filesize($file).PHP_EOL;


来源:https://stackoverflow.com/questions/25833610/filesize-giving-incorrect-result

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!