文件读写顺序问题
<?php<br /> <br /> function read($filename) {<br /> $fp = fopen($filename, 'rb');<br /> flock($fp, LOCK_SH);<br /> $data = @fread($fp, @filesize($filename));<br /> fclose($fp);<br /> return $data;<br /> }<br /> function write($filename, $data) {<br /> $fp = fopen($filename, 'ab');<br /> flock($fp, LOCK_EX);<br /> fwrite($fp, $data);<br /> fclose($fp);<br /> return mt_rand(1, 999);<br /> }<br /> <br /> $file = './wr.txt'; //原文件是空的<br /> echo 'r1: ', read($file), '|<br/>';<br /> echo 'w1: ', write($file, 'a'), '|<br/>';<br /> echo 'r2: ', read($file), '|<br/>';<br /> echo 'w2: ', write($file, 'b'), '|<br/>';<br /> echo 'r3: ', read($file), '|<br/>';<br /> <br /> ?>
r1: |<br /> w1: 745|<br /> r2: |<br /> w2: 404|<br /> r3: |
function read($filename) {<br /> $fp = fopen($filename, 'rb');<br /> flock($fp, LOCK_SH);<br /> clearstatcache(); //清除文件状态缓存<br /> $data = @fread($fp, @filesize($filename));<br /> fclose($fp);<br /> return $data;<br /> }<br /> function write($filename, $data) {<br /> $fp = fopen($filename, 'ab');<br /> flock($fp, LOCK_EX);<br /> fwrite($fp, $data);<br /> fclose($fp);<br /> return $data;//mt_rand(1, 999);<br /> }<br /> <br /> $file = './wr.txt'; //原文件是空的<br /> file_put_contents($file, ''); //清空源文件<br /> echo 'r1: ', read($file), '<br><font color='#FF8000'>------解决方案--------------------</font><br><br/>';<br /> echo 'w1: ', write($file, 'a'), '<br><font color='#FF8000'>------解决方案--------------------</font><br><br/>';<br /> echo 'r2: ', read($file), '<br><font color='#FF8000'>------解决方案--------------------</font><br><br/>';<br /> echo 'w2: ', write($file, 'b'), '<br><font color='#FF8000'>------解决方案--------------------</font><br><br/>';<br /> echo 'r3: ', read($file), '<br><font color='#FF8000'>------解决方案--------------------</font><br><br/>';<br /> readfile($file); //显示一下r1: