[ale] editing binary file with perl

Fletch fletch at phydeaux.org
Sat Apr 12 23:07:53 EDT 2003


>>>>> "John" == John Wells <jb at sourceillustrated.com> writes:

    John> I'm trying to emulate a file copy (don't ask) at a binary
    John> level with Perl.  The intent is a poc...my next step is to
    John> first strip off a certain number of bytes from the head of
    John> the file before printing the rest to another file, but I
    John> wanted to get this working first for a sanity check.

    John> Here's the code:

    John> open(FP, "<input.bin"); open(OP, ">output.bin");

ALWAYS CHECK THE RETURN VALUE FROM SYSTEM CALLS</broken record>

    John> while ($c=getc(FP)) { printf OP "%c", $c; }

You've already found the problem with this, so we' won't cover that.


There's a large bit of inherent inefficiency in processing a file
character by character.  You want to use read() or sysread() instead.
Or just use the File::Copy module.  Untested code follows.


#!/usr/bin/perl
use strict;

use IO::File ();
use File::Copy qw( cp );

die "usage: $0 offset in out" unless @ARGV == 2;

my( $offset, $infile, $outfile ) = @ARGV;

die "Offset `$offset' isn't numeric\n"
  unless $offset =~ /^\d+$/;

my $in = IO::File->new( "< $infile" ) 
  or die "Erorr opening input: $infile: $!\n";

my $out = IO::File->new( "> $outfile" )
  or die "Error opening output $outfile: $!\n";

## Seek $offset bytes into infile
$in->seek( $offset, 0 );

cp( $in => $out ) or warn "Copy failed: $!\n";

$in->close;
$out->close;

exit 0;

__END__

-- 
Fletch                | "If you find my answers frightening,       __`'/|
fletch at phydeaux.org   |  Vincent, you should cease askin'          \ o.O'
770 294-0820 (m)      |  scary questions." -- Jules                =(___)=
                      |                                               U
_______________________________________________
Ale mailing list
Ale at ale.org
http://www.ale.org/mailman/listinfo/ale





More information about the Ale mailing list