如何保持流位置时,使用gzstream与gzip文件

How to keep stream position when using gzstream with gzipped file?

本文关键字:gzstream gzip 文件 使用 何保持 位置      更新时间:2023-10-16

我必须处理用gzipped压缩的大文件。我需要访问这些线的一个子集,不一定是按顺序。因此,我想在记录我感兴趣的行的流位置时,一次遍历所有文件。然后,使用这些流位置来快速检索我需要的信息。

为此,我使用gzstream。但不幸的是,tellg似乎不能与这个包装器一起工作:

#include <iostream>
#include <fstream>
using namespace std;
#include <gzstream.h>
int main (int argc, char ** argv)
{
  string inFile;
  string line;
  system ("rm -f infile1.txt; echo "toto1ntoto2ntoto3" > infile1.txt");
  inFile = "infile1.txt";
  ifstream inStream;
  inStream.open (inFile.c_str());
  cout << inStream.tellg () << endl;
  getline (inStream, line);
  cout << inStream.tellg () << endl;
  inStream.close ();
  system ("rm -f infile1.gz; echo "toto1ntoto2ntoto3" | gzip > infile1.gz");
  inFile = "infile1.gz";
  igzstream igzStream;
  igzStream.open (inFile.c_str());
  cout << igzStream.tellg () << endl;
  getline (igzStream, line);
  cout << igzStream.tellg () << endl;
  igzStream.close ();
  return 0;
}

代码返回如下:

$ gcc -Wall test.cpp -lstdc++ -lgzstream -lz
$ ./a.out
0
6
18446744073709551615
18446744073709551615

是否有办法使这个工作与igzstream?或者我应该使用Boost gzip过滤器代替?任何代码片段将非常感谢;)

gzstream不支持在文件中查找,无论如何,这在gzip文件中不是一个特别有效的操作。您可以看看这个问题及其答案:随机访问gzip流

其中一个答案给出了一个来自zlib源代码的示例代码的链接,您可以使用它来帮助您实现gzstream中想要的功能。另一个答案建议使用一种变体的压缩格式,它可以更有效地支持查找。

Boost iostream可能支持查找,但是gzstream更容易使用和修改,所以我倾向于坚持使用