How to copy binary files in a Perl program

I have the following Perl code to make a copy of the binary 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 the code, the output binary is larger than the size of the input binary, because this perl code seems to add the character 0x0D (carriage return) to the character 0x0A (new line) in the input file, it is not there yet.

If I use chomp, then it is deleted even with valid 0x0A characters and does not put them in the output file.

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

2] How can I solve this problem using the File :: Copy module, any piece of code will be useful.

thanks.

-AD

+4
source share
2 answers

Always use tri-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 so easy to use that I don’t understand why you didn’t.

 use File::Copy; copy($in, $out) or die "Copy failed: $!"; 
+10
source

Call binmode in both files.

+4
source

All Articles