0

I have this content on 'test.txt' file: lucas
I want to seek pointer in the file and override info ahead. Supposed I do:

$f = new SplFileObject('test.txt', 'a');

$f->fseek(-5, SEEK_END);

var_dump($f->ftell());

$f->fwrite('one');

This should produce: oneas But the result of execution: lucasone

I'm crazy about the code logic or even doesn't works?

How is the right way to do what I want?

Lucas Batistussi
  • 2,283
  • 3
  • 27
  • 35

1 Answers1

3

You opened the file for appending:

$f = new SplFileObject('test.txt', 'a');

which means you cannot seek in the file. Instead, open it for reading and writing:

$f = new SplFileObject('test.txt', 'r+');

They also say it in the fseek documentation:

If you have opened the file in append (a or a+) mode, any data you write to the file will always be appended, regardless of the file position, and the result of calling fseek() will be undefined.

kuba
  • 7,329
  • 1
  • 36
  • 41
  • Well... I changed mode but the file was truncated! According PHP official site: w mode: "Open for writing only; place the file pointer at the beginning of the file and TRUNCATE THE FILE TO ZERO LENGTH. If the file does not exist, attempt to create it." I don't want truncate file, I want this result: "oneas" – Lucas Batistussi May 01 '12 at 16:11
  • OK when you are reading the docs... why don't you choose a different mode that doesn't truncate the file? It's right there on the same doc page. – kuba May 01 '12 at 16:15
  • 1
    e.g. "r+" does this: "Open for reading and writing; place the file pointer at the beginning of the file." I'll update my answer to this – kuba May 01 '12 at 16:16