1

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!

brian d foy
  • 129,424
  • 31
  • 207
  • 592
Magicked
  • 637
  • 3
  • 11
  • 20
  • You may also want to read http://stackoverflow.com/questions/1479741/why-is-three-argument-open-calls-with-lexical-filehandles-a-perl-best-practice and apply the practices therein. Global filehandles can lead you to a world of hurt later on when you're least expecting it. – Ether Apr 28 '10 at 14:45

1 Answers1

5

You might want to check if open doesn't return error.

open IN, "<$infile" or die "Can't open $infile: $!";
Dmitry Yudakov
  • 15,364
  • 4
  • 49
  • 53