我希望我的 perl 腳本從檔案中加載二進制資料。但是,如果檔案頭出現在檔案的開頭,則該檔案可以直接加載或需要解壓縮(zlib)_ISCOMPRESSED_。
我已經能夠成功加載未壓縮的檔案并識別標題:
(open my ($fh), "<", $fileName) or (return 0);
binmode $fh;
my $fileHeader;
sysread $fh, $fileHeader, 14;
if( $fileHeader eq "_ISCOMPRESSED_" ){
# Here, need to decompress the filestream and update the $fh to point toward uncompressed data
}
else{
# Read it from the begining
sysseek $fh,0,0;
}
# Read the data using the file handle
sysread $fh,$self->{'sig'},4;
sysread $fh,$self->{'version'},4;
我現在想用 Zlib 解壓縮資料塊并更新檔案句柄$fh以分配未壓縮的資料。
我應該怎么做,是否可以在不將未壓縮資料寫入磁盤的情況下做到這一點?
uj5u.com熱心網友回復:
perl 附帶的解壓縮模塊可以從現有的打開檔案句柄中讀取。讀取將從當前偏移量開始,從而可以輕松跳過標題。這些IO::Uncompress::*模塊特別創建了檔案句柄物件,這些物件可以與普通 I/O 函式一起使用以允許透明使用;創建它后,您的代碼并不關心它是壓縮源檔案還是純源檔案。就像是:
#!/usr/bin/env perl
use warnings;
use strict;
# I don't have a zlib-flate to test for sure; I think this is the right module
use IO::Uncompress::Inflate;
my $fileName = "data.compressed";
my $fh;
open my $realfh, "<:raw", $fileName
or die "Unable to open $fileName: $!\n";
read $realfh, my $header, 14;
if ($header eq "_ISCOMPRESSED_") {
$fh = IO::Uncompress::Inflate->new($realfh, AutoClose => 1)
or die "Unable to open decompression stream!\n";
} else {
seek $realfh, 0, 0;
$fh = $realfh;
}
read $fh, $self->{'sig'}, 4;
read $fh, $self->{'version'}, 4;
# etc.
close $fh;
如果您正在執行許多看起來像的小型輸入操作,我會使用readoversysread來利用內部緩沖。但重要的是要保持一致;在同一個檔案句柄上混合兩種形式會導致看似丟失資料的問題。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/504239.html
