【问题标题】:Read and write file bit by bit逐位读写文件
【发布时间】:2013-05-16 23:38:09
【问题描述】:

例如,有一个 .jpg 文件或其他文件。我想一点一点地读它。我这样做:

open(FH, "<", "red.jpg") or die "Error: $!\n";
my $str;
while(<FH>) {
    $str .= unpack('B*', $_);
}
close FH;

它给了我 $str 文件的 0101001。之后我这样做:

open(AB, ">", "new.jpg") or die "Error: $!\n";
binmode(AB);
print AB $str;
close AB;

但它不起作用。

我该怎么做?以及如何做到这一点,无论字节顺序如何(跨平台)都可以工作?

【问题讨论】:

    标签: perl file byte bit endianness


    【解决方案1】:

    问题:

    1. 你在阅读时也没有使用binmode
    2. 逐行读取二进制文件是没有意义的,因为它们没有行。
    3. 您不必要地为文件句柄使用全局变量。
    4. 回答您的问题的那个:您没有反转unpack

    open(my $FH, "<", "red.jpg")
       or die("Can't open red.jpg: $!\n");
    binmode($FH);
    my $file; { local $/; $file = <$FH>; }
    my $binary = unpack('B*', $file);
    
    open(my $FH, ">", "new.jpg")
       or die("Can't create new.jpg: $!\n");
    binmode($FH);
    print $FH pack('B*', $binary);
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2012-07-25
      • 2012-03-19
      • 2015-02-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多