我正在测试一个修改文件的工具,其中一个相当重要的功能就是告诉文件大小,特别是当文件仍处于打开状态时。
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我认为最终大小是文件仍然打开的结果,这就是我添加 fclose($ fp); ,但这没有任何区别。无论哪种方式,我都需要能够在文件仍处于打开状态时确定大小。
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.
最终大小应为20.有没有人知道这可能的原因以及如何解决这个问题?
The final size should be 20. Does anyone know the possible cause of this and how to work around it?
推荐答案as 此评论说明,您需要在调用 filesize()$ c之前调用 clearstatcache() $ c>再次。
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;更多推荐
filesize():给出错误的结果
发布评论