Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to copy binary files in Perl program

Tags:

perl

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

like image 521
goldenmean Avatar asked Dec 05 '22 00:12

goldenmean


1 Answers

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: $!";
like image 112
ephemient Avatar answered Dec 11 '22 14:12

ephemient