a+ and a mode with fopen()

7.9k views Asked by At

According to the manual, if you select a/a+ mode in the fopen() function, the file pointer will be placed at the end.

But why do I get 0 using the ftell() and the feof() still returns false? If the file pointer is at the end.

e.g:

$handle=fopen("./file.txt","w");
fwrite($handle,1234567890);
fclose($handle);
$handle=fopen("./file.txt","a+");
echo getc($handle);
fclose($handle);

I got 1, but shouldn't I get 0 if the file pointer is placed at the end?

3

There are 3 answers

2
Lightness Races in Orbit On

Right there in the documentation, near the top:

ftell() gives undefined results for append-only streams (opened with "a" flag).

3
Daniel W. On

a+ means, read from beginning, write to the end.

That's why you get a char back from the stream.

Internally you have two streams, STDIN and STDOUT.

0
Rashy On

"a" - Write only. Opens and writes to the end of the file or creates a new file if it doesn't exist.

"a+" - Read/Write. Preserves file content by writing to the end of the file.