0

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?

Jahid
  • 21,542
  • 10
  • 90
  • 108
ray
  • 29
  • 1
  • 2
  • Have you tried to actually write a string to the file instead of an integer? – ChristianM Jun 10 '15 at 21:07
  • Yes, I have. But the result is still the same. – ray Jun 10 '15 at 21:11
  • using the ftell() might be a bad idea. But if I choose a+ mode, why fgetc() still return the first character of the file? a+ mode put the file pointer in the end. – ray Jun 10 '15 at 21:23

3 Answers3

3

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.

Daniel W.
  • 31,164
  • 13
  • 93
  • 151
  • but the file pointer is placed in the end. doesn't that affect the fread(), fgets()? – ray Jun 10 '15 at 21:38
  • @ray: There is more than one file pointer, despite what PHP's abstraction makes you think. – Lightness Races in Orbit Jun 10 '15 at 21:40
  • It should be kept in mind that there is practically no use case where you want to read and write a file at the same time without beeing able to separate those steps, which is safer anyways. – Daniel W. Sep 02 '19 at 18:17
2

"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.

Rashy
  • 893
  • 9
  • 12
1

Right there in the documentation, near the top:

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

Lightness Races in Orbit
  • 378,754
  • 76
  • 643
  • 1,055
  • using the ftell() might be a bad idea. But if I choose a+ mode, why fgetc() still return the first character of the file? a+ mode put the file pointer in the end – ray Jun 10 '15 at 21:25
  • @ray: Probably a discrepancy between the internal read and write cursors. I guess PHP just _tries_ to keep them synched but doesn't go out of its way to detect when they begin life otherwise. When you open a file directly from POSIX in append mode, the write cursor is at the end _but the read cursor is at the start_. – Lightness Races in Orbit Jun 10 '15 at 21:26