perl – -B文件测试的可靠性如何?

当我打开一个sqlite数据库文件时,文件开头有很多可读文本 – 由于-B文件测试,sqlite文件错误地过滤的可能性有多大?
#!/usr/bin/env perl
use warnings;
use strict;
use 5.10.1;
use File::Find;

my $dir = shift;
my $databases;

find( {
    wanted     => sub {
        my $file = $File::Find::name;
        return if not -B $file;
        return if not -s $file;
        return if not -r $file;
        say $file;
        open my $fh,'<',$file or die "$file: $!";
        my $firstline = readline( $fh ) // '';
        close $fh or die $!;
        push @$databases,$file if $firstline =~ /\Asqlite\sformat/;
    },no_chdir   => 1,},$dir );

say scalar @$databases;

解决方法

有关-T和-B的 perlfunc手册页有如下说明:
The -T and -B switches work as follows. The first block or so of the file is
examined for odd characters such as strange control codes or characters with
the high bit set. If too many strange characters (>30%) are found,it's a -B
file; otherwise it's a -T file. Also,any file containing a zero byte in the
first block is considered a binary file.

当然,您现在可以对多个sqlite文件进行统计分析,解析“奇数字符”的“第一个块左右”,计算它们发生的概率,这样可以让您了解它的可能性. -B对sqlite文件失败.

但是,你也可以走简单的路线.可以失败吗?是的,这是一种启发式方法.那个坏人.所以不要使用它.

Unix上的文件类型识别通常通过评估文件内容来完成.是的,有些人已经为你完成了所有的工作:它被称为libmagic(产生文件命令行工具的东西).您可以在Perl中使用它,例如File::MMagic.

相关文章

1. 如何去重 #!/usr/bin/perl use strict; my %hash; while(...
最近写了一个perl脚本,实现的功能是将表格中其中两列的数据...
表的数据字典格式如下:如果手动写MySQL建表语句,确认麻烦,...
巡检类工作经常会出具日报,最近在原有日报的基础上又新增了...
在实际生产环境中,常常需要从后台日志中截取报文,报文的形...
最近写的一个perl程序,通过关键词匹配统计其出现的频率,让...