我正在尝试阅读带有以下代码的二进制文件:

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;

输入文件为16m; debug.txt仅为400k。当我在emacs中查看debug.txt时,最后两个字符是 ^a ^c(根据记事本++的soh和etx chars),尽管在debug.txt中存在相同的模式。文件中的下一行确实具有a ^o(si)char,我认为这是该特定字符的第一次出现。

如何在整个文件中阅读?

有帮助吗?

解决方案

如果你 真的 想要一次读取整个文件,使用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 对于全局变量。

其他提示

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);
}

我认为这不是使用SLURP模式,而是关于正确处理二进制文件的模式。

代替

$data = <F>;

你应该做

read(F, $buffer, 1024);

这只会读取1024个字节,因此您必须使用循环增加缓冲区或按部分读取整个文件。

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top