Reading a binary file in perl: Bad File Descriptor
- by Magicked
I'm trying to read a binary file 40 bytes at a time, then check to see if all those bytes are 0x00, and if so ignore them. If not, it will write them back out to another file (basically just cutting out large blocks of null bytes).
This may not be the most efficient way to do this, but I'm not worried about that. However, right now I'm getting a "Bad File Descriptor" error and I cannot figure out why.
my $comp = "\x00" * 40;
my $byte_count = 0;
my $infile = "/home/magicked/image1";
my $outfile = "/home/magicked/image1_short";
open IN, "<$infile";
open OUT, ">$outfile";
binmode IN;
binmode OUT;
my ($buf, $data, $n);
while (read (IN, $buf, 40)) { ### Problem is here ###
$boo = 1;
for ($i = 0; $i < 40; $i++) {
if ($comp[$i] != $buf[$i]) {
$i = 40;
print OUT $buf;
$byte_count += 40;
}
}
}
die "Problems! $!\n" if $!;
close OUT;
close IN;
I marked with a comment where it is breaking. Thanks for any help!