note 81325 deleted from function.fopen by cmb
| From: | cmb@php.net | Date: | Fri, 09 Sep 2016 22:32:52 +0000 |
| Subject: | note 81325 deleted from function.fopen by cmb | ||
| References: | 1 | Groups: | php.notes |
| Request: | Send a blank email to php-notes+get-206548@lists.php.net to get a copy of this message | ||
Note Submitter: jphansen at uga dot edu
----
If you open a file with r+ and execute an fwrite(), writing less to the file than what it originally
was, it will result in the difference being padded with the end of the file from the previous end of
the file. Example:
<?php
// Open file for read and string modification
$file = "/test";
$fh = fopen($file, 'r+');
$contents = fread($fh, filesize($file));
$new_contents = str_replace("hello world", "hello", $contents);
fclose($fh);
// Open file to write
$fh = fopen($file, 'r+');
fwrite($fh, $new_contents);
fclose($fh);
?>
If the end of the file was "abcdefghij", you will notice that the difference in
"hello world" and "hello", 6 characters, will be appended to the file, resulting
in the new ending: "efghij". To obviate this, fopen() with +w instead, which truncates the
file to zero length.