filesize():给出错误的结果 [英] filesize() : giving incorrect result

查看:196
本文介绍了filesize():给出错误的结果的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在测试一个修改文件的工具,其中一个相当重要的功能就是告诉文件大小,特别是当文件仍处于打开状态时。

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() 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():给出错误的结果的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆