goldenmean
goldenmean

Reputation: 18956

How to copy binary files in Perl program

I have the below Perl code to make a copy of a binary file that I have.

$in = "test_file_binary.exe";
$out = "test_out_binary.exe";
open(IN,$in) || die "error opening ip file: $!" ;
open(OUT,">$out") || die "error opening op file: $!" ;
while(<IN>)
{
 #chomp;
 print OUT $_;
}
close(IN);
close(OUT);

But this version of code, the output binary file is of more size than the input binary file size, because this perl code seems to add a 0x0D (Carriage return) character before a 0x0A (newline) character in the input file, it its not already there.

If I use chomp , then it is removed even valid 0x0A characters present, and did not put them in the output file.

1] How can I fix this in the code above.

2] How can I solve this using the File::Copy module, any example code snip would be useful.

thank you.

-AD

Upvotes: 4

Views: 3169

Answers (2)

ephemient
ephemient

Reputation: 204698

Always use three-arg open.

open IN, '<:raw', $in or die "Couldn't open <$in: $!";
open OUT, '>:raw', $out or die "Couldn't open >$out: $!";

my ($len, $data);
while ($len = sysread IN, my $data, 4096) {
    syswrite OUT, $data, $len;
}
defined $len or die "Failed reading IN: $!"

However, File::Copy is so easy to use I don't understand why you wouldn't.

use File::Copy;

copy($in, $out) or die "Copy failed: $!";

Upvotes: 13

aschepler
aschepler

Reputation: 72271

Call binmode on both file handles.

Upvotes: 4

Related Questions