File read/write sequence problems
'; 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?
Reply to discussion (solution)
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 an empty file_put_contents ($ file, ''); // clear the source file echo 'r1:', read ($ file), '|
'; Echo 'w1:', write ($ file, 'A'), '|
'; Echo 'R2:', read ($ file), '|
'; Echo 'w2:', write ($ file, 'B'), '|
'; Echo 'r3:', read ($ file), '|
'; Readfile ($ file); // Display ItR1: |
W1: a |
R2: a |
W2: B |
R3: AB |
AB
Clearstatcache -- clear the file status cache
This function caches the information of a specific file name. Therefore, you must call clearstatcache () only when you perform multiple operations on the same file name and the file information is not cached ().
Affected functions include stat (), lstat (), file_exists (), is_writable (), is_readable (), is_executable (), is_file (), is_dir (), is_link (), filectime (), fileatime (), filemtime (), fileinode (), filegroup (), fileowner (), filesize (), filetype (), and fileperms ().
It turns out to be a cache.