Having trouble reading a binary using ActivePerl?

I am trying to read a binary with the following code:

open(F, "<$file") || die "Can't read $file: $!\n";
binmode(F);
$data = <F>;
close F;

open (D,">debug.txt");
binmode(D);
print D $data;
close D;

Input file 16 M; debug.txt is only about 400 thousand. When I look at debug.txt in emacs, the last two characters are: ^ A ^ C (SOH and ETX characters, according to notepad ++), although the same pattern is present in debug.txt. The next line of the file has ^ O (SI) char, and I think the first occurrence of this particular character.

How can I read this whole file?

+3
source share
3 answers

, slurp. Slurp , $/ ( ) undef. , $/ .

my $data;
{
    open my $input_handle, '<', $file or die "Cannot open $file for reading: $!\n";
    binmode $input_handle;
    local $/;
    $data = <$input_handle>;
    close $input_handle;
}

open $output_handle, '>', 'debug.txt' or die "Cannot open debug.txt for writing: $!\n";
binmode $output_handle;
print {$output_handle} $data;
close $output_handle;

my $data our $data .

+5

TIMTOWTDI.

File::Slurp - , . .

use File::Slurp qw(read_file write_file);
my $data = read_file($file, binmode => ':raw');
write_file('debug.txt', {binmode => ':raw'}, $data);

IO::File API $/.

use IO::File qw();
my $data;
{
    my $input_handle = IO::File->new($file, 'r') or die "could not open $file for reading: $!";
    $input_handle->binmode;
    $input_handle->input_record_separator(undef);
    $data = $input_handle->getline;
}
{
    my $output_handle = IO::File->new('debug.txt', 'w') or die "could not open debug.txt for writing: $!";
    $output_handle->binmode;
    $output_handle->print($data);
}
+3

, slurp , .

$data = <F>;

you have to do

read(F, $buffer, 1024);

This will only read 1024 bytes, so you need to increase the buffer or read the entire part of the file in parts using a loop.

0
source

Source: https://habr.com/ru/post/1760094/


All Articles