Search code examples
phpunpack

`Type L: not enough input` when to unpack the target data


I get the job done to parse data from target file in binary form with the help of stackoverflow's friends.

<?php
    $handle = fopen('data', 'rb');
    fread($handle,64);
    while (!feof($handle)) {
        $bytes= fread($handle,32);
        print_r(unpack("La/fb/fc/fd/fe/ff/fg/fh",$bytes));
        echo "<br/>";
        }
    echo "finish";
    fclose($handle);
?>

I got the result ,one last bug remains here that can't solve myself.
1.why unpack(): Type L: not enough input, need 4, have 0 ?
2.how to fix it?

enter image description here


Solution

  • Change your loop to:

    while ($bytes = fread($handle, 32)) {
        print_r(unpack("La/fb/fc/fd/fe/ff/fg/fh",$bytes));
        echo "<br/>";
    }
    

    feof($handle) doesn't become true until after you've tried to read at the end of the file.

    So you're performing an extra fread(), which returns false, and then trying to unpack an empty byte string.