I wanted to know how fread function moves the file pointer inside the file.
lets consider the following scenario:
<?php
$file=fopen(binary.txt,rb);
fread($file,0x594);
function(fread($file,0x1a8), ....); // some function w/ first argument as fread O/P
?>
brief overview of the code:
it will open a binary file in read only mode. I wanted to know if my understanding is correct or not:
- The first invocation of the fread function will move the file pointer to position 0x594.
Since the position of the first byte in the binary file is considered 0, and fread function is reading 0x594 bytes, so what will be the new position of file pointer?
0x593 or 0x594?
- The second fread function will start reading from the previous file pointer position. So, everytime, there is an invocation of fread function, the position of file pointer is preserved?
Which means, in a sequence of fread function invocations, each fread function starts reading bytes from the position of the file pointer set by the previous fread function?
in this case, it will start reading bytes from position, 0x594 to (0x594+0x1a8) or 0x73c ?
thanks.
You can investigate this yourself, using ftell(). The current position of the file pointer is an inherent part of the file infrastructure, and PHP is simply riding on top of libc/glibc’s implementation of fopen/fread/etc…
However, consider this:
the file pointer will now be a position zero, because no data has been read.
file pointer will now be at position 500, because it’s read positions 0->499 (500 bytes) as part of the previous fread call.
still at position 500
etc…
Basically, use ftell() to check for yourself. ftell() is used to retrieve the CURRENT LOCATION of the filepointer, so you can use remember where you are. You can then use rewind(), fseek(), etc… to move the pointer all over, then jump right back to where you were without losing place: