Read and write file bit by bit

百般思念 提交于 2019-12-24 00:58:39

问题


There is a .jpg file for example or some other file. I want to read it bit by bit. I do this:

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

Well it gives me $str with 0101001 of the file. After that I do this:

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

but it doesn't work.

How can I do it? and how to do that that it would work regardless of byte order(cross-platform)?


回答1:


Problems:

  1. You're didn't use binmode when reading too.
  2. It makes no sense to read a binary file line by line since they don't have lines.
  3. You're needlessly using global variables for your file handles.
  4. And the one that answers your question: You didn't reverse the 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);


来源:https://stackoverflow.com/questions/16599200/read-and-write-file-bit-by-bit

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!