How insert a string before last character in a large file

AndroidDev :

I have a very large file that consists of a single string. Because of the size of the file, I do not want to read the entire string into memory.

The last character will always be a closing bracket ] as this string is a json array. I want to insert a small json object (represented as a string) immediately before that closing bracket. I have seen a few ideas, but cannot get anything to work.

As you can see, I am trying to open the file and use fseek to move the file pointer to just in front of the ]. Then I try to write the new string into the existing string at that position.

However, the effect of this is simply to append the new string to the end of the existing string, which is not what I want.

As a simplified example, let's say the file starts out containing this string:

[{"name":"alice","city":"london"}]

And then I want to add a second person to this list using this code:

$new_person = ",{\"name\":\"bob\",\"city\":\"paris\"}";

$filename = "people.json";
$fh = fopen($filename, "a+");
$filesize = filesize($filename);
$stat = fstat($fh);
fseek($fh, $stat[$filesize]-1);
fwrite($fh, $new_person);
fclose($fh); 

But what I wind up with is a file that contains this string:

[{"name":"alice","city":"london"}],{"name":"bob","city":"paris"}

My PHP skills are terrible. I can't tell if my fseek is pointing to the wrong spot or if the issue is elsewhere. Thanks for any help.

Niet the Dark Absol :

From the docs (emphasis mine):

a+: Open for reading and writing; place the file pointer at the end of the file. If the file does not exist, attempt to create it. In this mode, fseek() only affects the reading position, writes are always appended.

Use r+ mode instead, and instead of fstat you can do:

fseek($fh, -1, SEEK_END);

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=346850&siteId=1