filesize() : giving incorrect result

2019-08-10 14:35发布

问题:

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;


标签: php file io size