Perl如何在文件中二进制查找连续代码?
使用Perl在一个文件中查找一串二进制的字符(其中可能有0),如何处理?(要测试好的源代码) 问题点数:100、回复次数:1Top
1 楼AllCHN(大中国)回复于 2002-12-04 13:40:18 得分 100
刚好有一个类似程序,可做参考:
sub Search {
# 参数: 文件路径, 查找数据
# 如: myprg.exe, 0x45, 0x10, 0x84, 0, 0x55, ...
my $buff;
my $bytes_read;
my @find = @_;
my $filename = shift(@find);
my @readc;
my $alen = @find;
my $i;
my $j;
my $thisc;
my $found;
my $poscount;
return -1 if (!(-e $filename)); # 文件不存在
return -2 if (!open(FH, "+<$filename")); # 文件打开错误
binmode FH;
$bytes_read = read(FH, $buff, $alen - 1);
return -3 if ($bytes_read != $alen - 1); # 文件长度不足
@readc = split("", $buff);
foreach (@readc) {
$_ = ord($_);
}
unshift(@readc, 0);
$postcount = -1;
while ($bytes_read = read(FH, $buff, 1024)) {
for ($i = 0; $i < $bytes_read; $i++) {
$thisc = ord(substr($buff, $i, 1));
push(@readc, $thisc);
shift(@readc);
$poscount++;
$found = 1;
foreach ($j = 0; $j < $alen; $j++) {
if ($found != 0) {
if ($find[$j] != $readc[$j]) {
$found = 0;
}
}
last if ($found == 0);
}
last if ($found != 0);
}
last if ($found != 0);
}
if ($found != 0) {
# $poscount 为查找到的位置(从 1 开始计数)
close(FH);
return $poscount;
} else {
close(FH);
return -4; # 没有找到
}
}
Top




