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?

3
  • first read the content of file, then you concatenate "~" with content of file and write it using fwrite($file, "~".$file_content); Commented Nov 28, 2020 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. Commented Nov 28, 2020 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. Commented Nov 30, 2020 at 11:14

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.