0

I have noticed that in PHP (7.x), when you write to a file, it overwrites any existing characters. For example,

$file = fopen("test.txt", "r+");

/* test.txt contains
abc123
*/

fwrite($file, "~");

/* test.txt now contains
~bc123
*/

fclose($file);

This is a simple example - I could have stored all of the file contents, reopened in write mode, type ~, type the stored contents, done - but my file is going to become large (meaning variable size), and it contains multiple records, not just one like this example.

What I want is something like this:

$file = fopen("test.txt", "ir+"); // insert mode r+

/* test.txt contains
abc123
*/

fwrite($file, "~");

/* test.txt now contains
~abc123
*/

fclose($file);

Is there a way to do this?

Lakshya Raj
  • 1,669
  • 3
  • 10
  • 34
  • first read the content of file, then you concatenate "~" with content of file and write it using fwrite($file, "~".$file_content); – Bijay Regmi Nov 28 '20 at 21:55
  • @JackSparrow: as I had said in my question, I will not be able to do that because my file is larger than this example one. I do not wish to use that solution because, as the file grows larger, it will eventually become too large for that. I am using this for a project, and at the point when it becomes too large, no one will be able to use it anymore. It might even crash. So I am looking for an answer that can perform this operation, without any worries about memory space or anything like that. – Lakshya Raj Nov 28 '20 at 22:00
  • you can read large files line by line as a buffer of certain size using fgets(). Then you can modify line buffer as you need as per your question and write the buffer to same line. – Bijay Regmi Nov 30 '20 at 11:14

0 Answers0