File read/write order question this post was last edited by o911016 from 2013-03-1312: 45: 07 & lt ;? Phpfunction & nbsp; read ($ filename) & nbsp; {$ fp & nbsp; fopen ($ filename, & nbsp; rb); flock ($ fp, & nbsp; LOCK_SH); file read/write sequence problems
This post was last edited by o911016 at 12:45:07
Function 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'; // The original file is empty.
Echo 'r1: ', read ($ file),' |
';
Echo 'w1: ', write ($ file, 'A'),' |
';
Echo 'R2: ', read ($ file),' |
';
Echo 'w2: ', write ($ file,' B '),' |
';
Echo 'r3: ', read ($ file),' |
';
?>
Results after actual execution:
r1: |
w1: 745|
r2: |
w2: 404|
r3: |
The execution sequence is different from that of the PHP statement,
The actual order is "r1-> r2-> r3-> w1-> w2 ".
I tried to change the lock LOCK_SH added to the read file to LOCK_EX, and the result is still the same as the above sequence.
How can I make the read/write order conform to the statement sequence "r1-> w1-> r2-> w2-> r3?
------ Solution --------------------
This post was last edited by xuzuning at 12:56:42
The real cause is that the file size ($ filename) is always 0 due to file status cache.
Function read ($ filename ){
$ Fp = fopen ($ filename, 'RB ');
Flock ($ fp, LOCK_SH );
Clearstatcache (); // clear the file status cache
$ 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'; // The original file is empty.
File_put_contents ($ file, ''); // clear the source file
Echo 'r1: ', read ($ file ),'
------ Solution --------------------
';
Echo 'w1: ', write ($ file, 'A '),'
------ Solution --------------------
';
Echo 'R2: ', read ($ file ),'
------ Solution --------------------
';
Echo 'w2: ', write ($ file,' B '),'
------ Solution --------------------
';
Echo 'r3: ', read ($ file ),'
------ Solution --------------------
';
Readfile ($ file); // Display It
R1:
------ Solution --------------------
W1:
------ Solution --------------------
R2: