读写文件 [英] Read and write file bit by bit
本文介绍了读写文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
例如,有一个.jpg文件或其他文件.我想一点一点地阅读它.我这样做:
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;
好吧,它为我提供了$ str并带有文件0101001的信息.之后,我这样做:
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;
但它不起作用.
我该怎么办?以及如何在不考虑字节顺序(跨平台)的情况下都能正常工作?
How can I do it? and how to do that that it would work regardless of byte order(cross-platform)?
推荐答案
问题:
- 您在阅读时也没有使用
binmode
. - 因为没有行,所以逐行读取二进制文件是没有意义的.
- 您不必要在文件句柄中使用全局变量.
- 回答您问题的人:您没有颠倒
unpack
.
- You're didn't use
binmode
when reading too. - It makes no sense to read a binary file line by line since they don't have lines.
- You're needlessly using global variables for your file handles.
- 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);
这篇关于读写文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文