I'm reading a binary file in PHP:
$File = fopen('simplefile', 'rb');
// Random stuff
fseek($File, $APosition);
for($I = 0; $I < 10; $I ++ ){
var_dump(unpack('V', fread($File, 4)));
}
fclose($File);
However this does not give correct output for that position (it is giving 6357101
not 4294967295
as expected - I've checked using a hex editor).
However, this work and gives the correct values:
$File = fopen('simplefile', 'rb');
// Random stuff
fseek($File, $APosition);
for($I = 0; $I < 10; $I ++ ){
fseek($File, ftell($File)); // What is this line doing?
var_dump(unpack('V', fread($File, 4)));
}
fclose($File);
This however, I don't understand as surely fseek($File, ftell($File));
does absolutely nothing? What is that line doing and how can I read the correct values without errors?
This segment of the file is just 0xFF
repeated several hundred times.
I set up a file of all FF
bytes, and the loop correctly reads -1 ten times, which is 4294967295 unsigned. I can't reproduce the value you get.
The value you are getting, 6357101
, corresponds to the bytes 6D 00 61 00
. That is the characters 'ma' encoded in UTF-16, although it could also mean other things.
I think the file or the content of the file is not what you think it is, or you are reading from the wrong place.
fseek($File, ftell($File)); // What is this line doing?
It should do nothing. If it doesn't do nothing I can only speculate that perhaps the file is corrupt on disk, or your copy of PHP is borked, or your computer has gone quietly mad.
If you dont use that line, that mean, you are still reading the first 4 Bytes in Loop. You need do seek.
sometxtfile.txt
aaaabbbbcccc
Without that line it ould be like:
This will return aaaaaaaaaaaa
:
$File = fopen('sometxtfile.txt', 'rb');
echo fread($File, 4);
echo fread($File, 4);
echo fread($File, 4);
With that line it is like:
This will return aaaabbbbcccc
:
$File = fopen('sometxtfile.txt', 'rb');
echo fread($File, 4);
fseek($File, ftell($File));
echo fread($File, 4);
fseek($File, ftell($File));
echo fread($File, 4);
fseek($File, ftell($File));
See PHP documentation for further info.