PrimeLord has asked for the wisdom of the Perl Monks concerning the following question:

I am seeking some wisdom on how to use File::Binary. I am looking to read in a binay file and once I hit a specific text string start reading and storing x number of ints and shorts.

It seems that File::Binary is the module to do that, but I have to admit I am completely lost as how to use it. I see the methods to read in 16 and 32 bit unsigned ints, but I don't understand how you read in the specific ones you are looking for.

I suppose using the seek method may help, but I don't know exactly where in the file the data structures I need begin which is why I have te search for the text string. Anyone have an code examples or some guidance for me on using this utility? Thanks!

-Prime

Replies are listed 'Best First'.
Re: File::Binary help
by ambrus (Abbot) on Jan 24, 2005 at 13:13 UTC

    I would do this with perl's builtin functions, not File::Binary.

    To search for a string in a binary file, you can use a sliding window, such as

    my $s = "YOUR_NEEDLE"; open my $f, "<", "YOUR_FILENAME" or die "open error: $!"; binmode $f o +r die "binmode error: $!"; my($b0, $b1) = ""; my($r, $g) = 0; do { $b1 = $b0; $r = read($f, $b0, 1024); defined($r) or die "read err +or: $!"; $r == 0 and die "string not found"; } until 0 <= ($g = index($b1 . $b0, $s)); my $pos = tell($f) - length($b0) - length($b1) + $g + length($s);

    (Update: the easy way is { local $/ = $s; defined(readline $f) or die "error read: $!"; } $pos = tell($f);, but that reads a large chunk of file to memory.)

    Then you can seek to $pos, and read the data from there with read. You can interpret binary data with unpack.

    Update: corrected error in first sentence, noticed by BrowserUk.

Re: File::Binary help
by aquarium (Curate) on Jan 24, 2005 at 09:49 UTC
    what binary file are you trying to read? what's the specific text string? Could you start by reading the file in ints to find the specific text string?
    the hardest line to type correctly is: stty erase ^H