in reply to Reading Binary file confusion

Sorry here's some example code
#! c:/perl/bin/perl; use strict; use warnings; #======================= # Define VARS # ====================== my $RECORD_SIZE = 40; my $ID = 0; my $size = 20; # Num of Bytes to read from fi +le my $offset = 0; # Offset to file reading. my $MASK = 'H4C3H4b12H4'; my $file = "FileName"; open( FILE, $file ) || die print "Can not open file"; # open file binmode FILE; # Turn on Binary mode # Read Header for the record. while ( sysread( FILE, $data, $size) ){ #Filehandle,str +ing,length,offset my ($flag,$format,$blocks,$source,$no,$time,$type) = unpack $MASK, + $data; print "Header: $flag\n"; print "Header Data:",unpack $MASK, $data; print "\n"; # Check integity of the header. if ( $flag != 1234 ) { die print "Ill formed header. File may be corrupt."; # Read the remainder of the record. $size = ( ( $RECORD_SIZE * $blocks ) - 20 ); sysread( FILE, $data, $size ); #Filehandle,string,length,offset # Debugging stuff to match Hex editor to file to determine what is goi +ng on. my $long = length($data); print "Size of Data portion of record: $long \n"; my $temp = "H" . $long; #print $temp; my $alldata = unpack $temp, $data; print "Data: $alldata\n"; } close FILE;

Replies are listed 'Best First'.
Re: Re: Reading Binary file confusion
by YuckFoo (Abbot) on Mar 11, 2002 at 22:24 UTC
    I think your header is a fixed size? It reads correctly for the first header, but then you change $size in the loop for the data portion. For the next header, $size is incorrect, having the size of the last data portion. I quit looking when I saw this, it may or may not fix all your problems.

    YuckFoo

      I have serious Egg on my face. YuckFoo is correct, after pulling my data I did not reset my size back to the size of the header. Once I did this my sample script ran through the entire bin file checking the header Ids and made it through the file no problem. I will still have to go back and verify this but my problem seems to be solved. Thank you all!!!

      As a side note, I have always been impressed with the fact that no matter what the question may be, or in my case how dense the writer of the question, someone always answers whatever gets posted. This may not always be the case but it has been for me. Thanks you all. Because it is this type of support that makes this site what it is, one of my favorites