简体   繁体   中英

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

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: $!";

在两个文件句柄上调用binmode

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM