1

say we have this file test.txt:

{}

And we want to add text between { and }.

I tried this:

$f = new SplFileObject($filepath, 'r+');
$f->fseek(1);
$f->fwrite('test');

but the output is {test, I tried also other modes like w+ (result-> test), a+ (result-> {}test

EDIT: forgot to tell that I dont want to load all the contents of the file to the memory, thats why I using SplFileObject

Almis
  • 3,684
  • 2
  • 28
  • 58
  • 1
    Well, one way would be to work with classic string manipulation functions (str_*), but that would probably be very error prone and not really flexible. What exactly are you trying to achieve? Looks like you've got a Json object in there - why not just read the whole file, convert the content back into a Json-object, modify it as you like and then serialize it again? – Quasdunk Apr 24 '14 at 14:45
  • @Quasdunk yes I want to write/read json but I have big json file and I dont want load it to the memory – Almis Apr 24 '14 at 14:47
  • A file rarely has the semantics of `insert`. They are generally limited to append, overwrite, and delete. – wallyk Apr 24 '14 at 14:47

3 Answers3

1

Read the whole content of the file as a string, and write something in it: Insert string at specified position

Then save the file with W+

Community
  • 1
  • 1
Balázs Varga
  • 1,797
  • 2
  • 16
  • 32
1

You have to load the file into memory for this kind of transformation—at least a portion of the file. That's what memory is for. You could read one file and write another with modifications to avoid keeping the entire file in memory.

If necessary, then delete the old file and rename the new file to the old.

wallyk
  • 56,922
  • 16
  • 83
  • 148
0

It's not possible to insert something into the middle of a file. All you can do is read in all the data after the position you want to write, and write it back later.

Zebra North
  • 11,412
  • 7
  • 37
  • 49