Home  >  Article  >  Backend Development  >  文件读写顺序有关问题

文件读写顺序有关问题

WBOY
WBOYOriginal
2016-06-13 12:52:03808browse

文件读写顺序问题

本帖最后由 o911016 于 2013-03-13 12:45:07 编辑
<?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: |


根据结果发现,执行顺序和PHP语句的顺序不同,
实际上的顺序是“r1 -> r2 -> r3 -> w1 -> w2”。
我试过把读文件所加的锁LOCK_SH改成LOCK_EX,结果还是和上面的顺序一样。

怎样才能让读写顺序符合语句顺序“r1 -> w1 -> r2 -> w2 -> r3”来执行?

------解决方案--------------------
本帖最后由 xuzuning 于 2013-03-13 12:56:42 编辑 真正的原因是文件状态缓存造成 filesize($filename) 始终为 0 
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: 
------解决方案--------------------

w1: a
------解决方案--------------------

r2: a
Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn