fwrite writing from beginning without removing

后端 未结 8 1576
误落风尘
误落风尘 2021-01-01 05:08

I am using PHP and fwrite code, but I want every write position to start from the beginning of the file without erasing it\'s content. I am using this code but it is writing

8条回答
  •  清酒与你
    2021-01-01 05:48

    So you want to write at the beginning of a file, leaving all of its current contents after the new data? You'll have to grab its existing contents first, then append it back into the file once you've overwritten with your new data.

    $file = 'aaaa.txt';
    $oldContents = file_get_contents($file);
    $fr = fopen($file, 'w');
    fwrite($fr, "text");
    fwrite($fr, $oldContents);
    fclose($fr);
    

    If you want to avoid loading the original file's contents into memory in your PHP script, you might try first writing to a temp file, using a loop buffer or system calls to append the contents of your original file to the temp file, then remove the original file and rename your temp file.

提交回复
热议问题