Fread cannot read newly added line

I have this code for writing a line to the new.txt file (already consisting of 2 lines), and after that a copy (backup) of this txt content to the new tmp.txt file but fread () does not skip the new line from the new file. txt to copy to tmp.txt tmp.txt suppose you have 3 lines inside, but there is no new line added.

$File ="new.txt"; $File2="tmp.txt"; //write into file $handle = fopen ($File, 'a') or die("Cannot open File"); fwrite($handle,"some string"); fclose($handle ); //copy file $handle2= fopen ($File, 'r') or die("Cannot open File"); $content = fread($handle2, filesize($File)); fclose($handle2); $handle3 = fopen ($File2, 'w') or die("Cannot open File"); fwrite($handle3,$content); fclose($handle3 ); 
-1
source share
2 answers

From the documentation for filesize :

Note. The results of this function are cached. See clearstatcache() more details.

By following this link, you will receive the following additional information that fully answers your question:

When you use stat () , lstat (), or any of the other functions listed in the list of affected functions (see below), PHP caches the information returned by these functions to provide better performance. However, in some cases, you may need to clear the cached information. For example, if the same file is checked several times within the same script, and this file can be deleted or modified during this script operation, you can choose to clear the status cache. In these cases, you can use the clearstatcache() function to clear information that PHP caches the file.

Documentation is your friend; use it!

-1
source

The fread () command takes as the second argument the length of the content to read, not the size of the file, which is not the same. In any case, it would be better to use copy () instead of fread () to duplicate the file:

 //replacement for your copy file copy($handle1, $handle2); 
-1
source

Source: https://habr.com/ru/post/1479708/


All Articles