file - perl 文件到十六进制数 82?
问题描述
尝试对文件进行二进制到十六进制转换。我可以输出十六进制,但是当我尝试将结果输出到文件时,变量返回字符串“82”。我不明白为什么;就像所有的事情很可能是简单的事情。
#!/usr/bin/perl -w
use strict;
my $blockSize = 1024;
my $fileName = $ARGV[0];
my $hexName = $ARGV[1];
open(F,"<$fileName") or die("Unable to open file $fileName, $!");
binmode(F);
my $buf;
my $ct=0;
while(read(F,$buf,$blockSize,$ct*$blockSize)){
foreach(split(//, $buf)){
printf unpack ("H*", $_); #prints the hex stream to terminal just fine
open(H,">$hexName") or die("Unable to open file $fname, $!");
binmode (H);
printf H unpack ("H*", $_);
close (H);
}
print "\n";
$ct++;
}
close(F);
输出
perl rawrHexFile.pl test.png file.hex
89504e470d0a1a0a0000000....
mookie@temple:/srv/bench % cat file.hex 82
cat file.hex
82
谢谢。
这是我的最终代码。的情况下
use strict;
my $fileName = $ARGV[0];
my $hexName = $ARGV[1];
my $hexCodeFile = $ARGV[2];
my $hexDecodeFile = $ARGV[3];
my $blockSize = -s $fileName;
my $buf;
open(F,"<$fileName") or die("Unable to open file $fileName, $!");
binmode(F);
open(H,">$hexName") or die("Unable to open file $hexName, $!");
read(F,$buf,$blockSize);
print H unpack ("H*", $buf);
close (H);
close(F);
解决方案
您为输入文件的每个字节重新创建文件(打开>),因此您只能获得输入文件的最后一个字节的输出。在循环外打开文件。
此外,您继续追加$buf
而不是替换其内容,因此您的输出将看起来像 AABAABCABCDABCDE 而不是所需的 ABCDE(其中每个字母代表 1024 字节输入的输出)
固定的:
use strict;
use warnings qw( all );
use constant BLOCK_SIZE => 64*1024;
my ($in_qfn, $out_qfn) = @ARGS;
open(my $in_fh, '<:raw', $in_qfn)
or die("Unable to open \"$in_qfn\": $!\n");
open(my $out_fh, '>', $out_qfn)
or die("Unable to open \"$out_qfn\": $!\n");
while (1) {
defined( my $rv = sysread($in_fh, my $buf, BLOCK_SIZE) )
or die("Unable to read from \"$in_qfn\": $!\n");
last if !$rv;
print($fh_out unpack("H*", $buf))
or die("Unable to write to \"$out_qfn\": $!\n");
}
close($fh_in);
close($fh_out)
or die("Unable to write to \"$out_qfn\": $!\n");
以上解决了您程序中的许多其他问题:
- 使用 2-arg open
- 不带模式使用 printf
- 不必要地使用全局变量
unpack H*
处理任何长度的字符串时不必要地拆分输入- 当 Perl 从操作系统读取 4 KiB 或 8 KiB 块时,1 KiB 读取效率低下
- 对文本文件使用 binmode
推荐阅读
- firebase - Firebase 电子邮件链接仅适用于现有用户(禁止新用户)
- c - 为什么这段代码会给我运行时错误?C
- r - 有没有办法让 R 中的 arrows() 绘制“T”形箭头而不是反向箭头?
- git - 从另一个特性中变基特性来开发
- dynamic-programming - 最长递增子序列背后的算法
- dd - 如何将rootfs制作成img?
- javascript - 为什么这个 javascript 变量输出“未定义”和正确的输出?
- c# - 使用 Xamarin 返回 0 获取当前 gps 位置
- javascript - 异步更新网站的代码不起作用?详细说明
- sql - ALTER SCHEMA NAME 是否会影响对 Redshift 中架构的权限授予