note 81325 modified in function.fopen by danbrown
| From: | danbrown@php.net | Date: | Mon, 08 Jun 2009 23:32:21 +0000 |
| Subject: | note 81325 modified in function.fopen by danbrown | ||
| References: | 1 | Groups: | php.notes |
| Request: | Send a blank email to php-notes+get-156542@lists.php.net to get a copy of this message | ||
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.
--was--
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:
<?
// 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.
http://php.net/manual/en/function.fopen.php