简体   繁体   中英

PHP Overwriting at a specific location in a file

I am trying to write a text at a specific position in a file that already has some content. After writing I find the file truncated to the size of the text plus fseek position and the first characters with value 0. Is this the normal behaviour or am I missing something? I want to mention that I'm trying to avoid loading the file into memory and writing it back.

$file = fopen("text.txt","w");
fseek($file,3);
fwrite($file,"Hello");
fclose($file);

You need to open the file in c mode, else it's truncated on fopen :

$file = fopen("text.txt","c");

See http://php.net/manual/de/function.fopen.php for a documentation of all file open modes and what exactly they do. Also see the http://www.php.net/manual/en/function.fseek.php manual

Yes this is normal behaviour :

fopen($file, "w") :

place the file pointer at the beginning of the file and truncate the file to zero length.

fseek() :

In general, it is allowed to seek past the end-of-file; if data is then written, reads in any unwritten region between the end-of-file and the sought position will yield bytes with value 0 . [..] If you have opened the file in append (a or a+) mode, any data you write to the file will always be appended, regardless of the file position, and the result of calling fseek() will be undefined.

You probably want to open the file in a non truncating write mode (eg "c" but not "a" ).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM