2

I have file called denem.txt and has content

123456789
123456789
123456789

When we open a file with mode 'a+b' PHP is supposed to place the pointer to end of the file which means when I try to get a character with fgetc function it should return False since feof is true. However when I use a code something like

while (false !== ($char = fgetc($file))) {
    echo "$char\n";
}

I get 1 2 3 4 5 6 7 8 9 1 2 3 4 5 6 7 8 9 1 2 3 4 5 6 7 8 9 . -> that is strange because I haven't used rewind() and pointer must be at the end of the file means fgetc must return a False. ftell returns int 0 means pointer is at the begining of the file. However when I try to write something to the file with fwrite which uses pointer's current position it supposed to write it to the begining of the file if ftell doesn't lie to us. But when I use fwrite guess what happens, it writes it to the end of the file and my file becomes

123456789
123456789
123456789Test

Do you have any idea about this?

ufucuk
  • 475
  • 9
  • 21

2 Answers2

3

You need to understand the a+ mode.

It opens the file for reading and appending (writing at end of file). The file is created if it does not exist. The initial file position for reading is at the beginning of the file, but output is always appended to the end of the file.

There is just one pointer which initially is at the start of the file but when a write operation is attempted it is moved to the end of the file. You can reposition it using fseek or rewind anywhere in the file for reading, but writing operations will move it back to the end of file.

codaddict
  • 445,704
  • 82
  • 492
  • 529
0

I just figured out something else when I open a file with a+b lets say a file with no content

$pointer = fopen("deneme.txt","a+b");
fwrite($pointer, rand(0,9));
echo fgetc($pointer);
echo ftell($pointer);
echo fgetc($pointer);

prints always "1" to screen. OK, if you want to read the file you rewind than there is no problem, but if I don't use rewind as in example, ftell says pointer's position is 1. So if a+ is APPEND mode and places pointer at the end of the file ftell is lying, if it is not lying why fgetc doesn't return any character? Your answer would be "Just use rewind()" but I'm really confused about this!

ufucuk
  • 475
  • 9
  • 21