in reply to Re^2: How to read number of block in binary files?
in thread How to read number of block in binary files?

This is because if the block contain 2 record the length is 604 while 3 record is 890 bytes. So that why i set $offset -= 286. is it correct ?

read( DATA, $data, BLOCKLEN, $offset );

is the same as saying:

read( DATA, my $temp, BLOCKLEN );
substr( $data, $offset ) = $temp;

and then the next statement:

my $blockhdr = unpack "H*", substr($data, 0, BLOCKHDR);

always extracts data from offset 0, at the beginning of $data

You need to read BLOCKHDR + BLOCKDATA data first, extract the $total_record value from that and then read $total_record * 286 data to get the actual records.

Replies are listed 'Best First'.
Re^4: How to read number of block in binary files?
by bh_perl (Monk) on Mar 10, 2009 at 02:31 UTC

    Hi.. Thank for your info.. that very helpful.. But could you guide me how could i read the binary files until end of file ?..

    This is my latest code:-

    if ($fname) { open (OUTPUT, ">$fname.tmp") or die "Can't open $fname.tmp $!\ +n"; open (DATA, "<$fname") or die "Can't open $fname $!\n"; binmode DATA; read(DATA, $data, BLOCKHDR); $blockhdr = unpack "H*", $data; read(DATA, $data, BLOCKDATA); $blockdt = unpack "H*", $data; my $t_cdr = hextoint(reverse_str(substr($blockdt,4))); my $blocklen = $t_cdr * 286; read(DATA, $data, $blocklen); my $record = unpack "H*", $data; close(DATA); close(OUTPUT); } else {

      This is UNTESTED but you may want code something like this:

      Update to while loop conditional.

      use constant HEADER_LEN => 32; use constant RECORD_LEN => 286; use constant DUMMY => "\0" x RECORD_LEN; if ( $fname ) { open my $OUTPUT, '>:raw', "$fname.tmp" or die "Cannot open '$fname +.tmp' $!"; open my $INPUT, '<:raw', $fname or die "Cannot open '$fname +' $!"; RECORD: { my ( $offset, $bytes_read, $header ) = ( 0, 0, '' ); # while ( $bytes_read < HEADER_LEN ) { while ( $offset < HEADER_LEN ) { defined( $bytes_read = read $INPUT, $header, HEADER_LEN - +$offset, $offset ) or die "Cannot read from '$fname' $!"; $bytes_read or last RECORD; # EOF $offset += $bytes_read; } # format may be either 'x30 n' or 'x30 S' depending on endiane +ss? my $total_record = unpack 'x30 n', $header; my $records_len = $total_record * RECORD_LEN; ( $offset, $bytes_read, my $data ) = ( 0, 0, '' ); # while ( $bytes_read < $records_len ) { while ( $offset < $records_len ) { defined( $bytes_read = read $INPUT, $data, $records_len - +$offset, $offset ) or die "Cannot read from '$fname' $!"; $bytes_read or last RECORD; # EOF $offset += $bytes_read; } $header = pack 'a30 n', $header, 3; print $OUTPUT $header, $data, $total_record == 2 ? DUMMY : ''; redo; } }