Beefy Boxes and Bandwidth Generously Provided by pair Networks
Don't ask to ask, just ask
 
PerlMonks  

Re^2: Reading Binary files in Perl

by pranjali_malode (Initiate)
on Aug 25, 2010 at 12:58 UTC ( #857185=note: print w/replies, xml ) Need Help??


in reply to Re: Reading Binary files in Perl
in thread Reading Binary files in Perl

Below is the structure or format of data in binary file: <structure> Offset Field Name size 0x0 magic_numbe 8 0x8 retry_count 1 0x9 number_record 1 0x10 dc_timestamp 8 <\structure> and the code is:
open(FH, "<DCdata.bin") or die "Can't open DCdata.bin file for reading +!"; binmode(FH); while (<FH>) { $index = 0; foreach $field_name (keys (%disk_structure)) { $value = read (FH, $buffer, ($field_name * 8), 0); print tell (FH); print "\n"; } foreach $f_name (keys (%disk_structure_record)) { $value_record = read (FH, $buffer, ($f_name * 8), 0); #print tell (FH)\n; } } close(FILE);

Replies are listed 'Best First'.
Re^3: Reading Binary files in Perl
by BrowserUk (Pope) on Aug 25, 2010 at 13:16 UTC

    If your file consists of 18 character records, then the easiest way to read it is to set the input record separator ($/) to a reference to the number of bytes per record: $/ = \18;. This causes readline() (<FH>) to read the file as a series of fixed length records. You can then unpack the fields within each record very easily:

    #! perl -slw use strict; =comment Offset Field Name size 0x0 magic_numbe 8 0x8 retry_count 1 0x9 number_record 1 0x10 dc_timestamp 8 =cut open( FH, '<', DCdata.bin" ) or die "Can't open DCdata.bin file for reading!"; binmode(FH); $/ = \18; ## set record size while( <FH> ) { my( $magic, $retry, $recnum, $timestamp ) = unpack 'A8 C C A8', $_ +; ## Do something with the information?? } close FH;

    Examine what is said, not who speaks -- Silence betokens consent -- Love the truth but pardon error.
    "Science is about questioning the status quo. Questioning authority".
    In the absence of evidence, opinion is indistinguishable from prejudice.
Re^3: Reading Binary files in Perl
by Corion (Pope) on Aug 25, 2010 at 12:59 UTC

    A hash is not ordered, so it makes no sense to read the (ordered) elements from a file in a foreach loop over the hash keys.

Log In?
Username:
Password:

What's my password?
Create A New User
Node Status?
node history
Node Type: note [id://857185]
help
Chatterbox?
holli idles
[holli]: not true

How do I use this? | Other CB clients
Other Users?
Others exploiting the Monastery: (5)
As of 2017-09-24 13:00 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?
    During the recent solar eclipse, I:









    Results (274 votes). Check out past polls.

    Notices?