读取给定字节数的大文件(二进制或文本)的开头和结尾的最有效方法是什么?
示例:
=head2 read_file_contents(file, limit)
Given a filename, returns its partial content in bytes, with number of truncated bytes
=cut
sub read_file_contents
{
my ($file, $limit) = @_;
my $rv;
# Starting and ending number of bytes to read
$limit = $limit / 2;
# Reading beginning of file
my $start;
# code goes here
# Reading end of a file
my $end;
# code goes here
$rv = $start . "\n\n\n truncated N bytes of data \n\n\n" . $end;
return $rv;
}
主要目标是能够在不处理整个文件的情况下快速有效地获取其开始和结束字节。读取整个文件然后按需要的方式substr
不是问题,但它不能很好地处理 10 Gb 以上的文件。
任何解决方案将不胜感激。
最佳答案
open(my $fh, "<", $file) or die "...";
my $r = read($fh, $start, $limit) or die "...";
die "short read\n" unless $r == $limit;
seek($fh, -$limit, 2) or die "...";
$r = read($fh, $end, $limit) or die "...";
关于perl - 在 Perl 中读取文件第一个和最后一个字节数的最有效方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65290001/