<?phpfunction read($filename) { $fp = fopen($filename, 'rb'); flock($fp, LOCK_SH); $data = @fread($fp, @filesize($filename)); fclose($fp); return $data;}function write($filename, $data) { $fp = fopen($filename, 'ab'); flock($fp, LOCK_EX); fwrite($fp, $data); fclose($fp); return mt_rand(1, 999);}$file = './wr.txt'; //原文件是空的echo 'r1: ', read($file), '|<br/>';echo 'w1: ', write($file, 'a'), '|<br/>';echo 'r2: ', read($file), '|<br/>';echo 'w2: ', write($file, 'b'), '|<br/>';echo 'r3: ', read($file), '|<br/>';?>
r1: |w1: 745|r2: |w2: 404|r3: |
真正的原因是文件状态缓存造成 filesize($filename) 始终为 0
function read($filename) { $fp = fopen($filename, 'rb'); flock($fp, LOCK_SH); clearstatcache(); //清除文件状态缓存 $data = @fread($fp, @filesize($filename)); fclose($fp); return $data;}function write($filename, $data) { $fp = fopen($filename, 'ab'); flock($fp, LOCK_EX); fwrite($fp, $data); fclose($fp); return $data;//mt_rand(1, 999);} $file = './wr.txt'; //原文件是空的file_put_contents($file, ''); //清空源文件echo 'r1: ', read($file), '|<br/>';echo 'w1: ', write($file, 'a'), '|<br/>';echo 'r2: ', read($file), '|<br/>';echo 'w2: ', write($file, 'b'), '|<br/>';echo 'r3: ', read($file), '|<br/>';readfile($file); //显示一下
明白了,原来是缓存的缘故。