代码之家  ›  专栏  ›  技术社区  ›  Irad K

使用libarchive将gzip文件解压缩到内存

  •  4
  • Irad K  · 技术社区  · 5 年前

    我试图以编程方式将gzip文件解压到内存中并模拟命令 gzip -d file.gz libarchive project . Accept-Encoding: gzip, deflate

    这是我试图读取的文件。我不希望不工作,因为gzip文件没有条目(它被压缩为流)并且 archive_read_next_header 尝试从arcihve中读取下一个文件。

    是否有任何替代此函数的方法从压缩文件中提取整个数据。

    archive_read_support_format_raw(archive); 
    archive_read_support_filter_all(archive);
    archive_read_support_compression_all(archive)
    
    archive_read_open_memory(archive, file_data, file_size);
    struct archive_entry *entry;
    la_ssize_t total, size;
    char *buf;    
    int status = archive_read_next_header(archive, &entry);
    

    也许有人可以发布最小的代码示例来解决这个问题? 另外,是否有一个选项来确定gzip存档文件是否有条目?

    1 回复  |  直到 5 年前
        1
  •  1
  •   tangy    5 年前

    一种可能的选择是使用 boost::iostreams 这个库带有一个内置的gzip过滤器,并允许你想要什么-从内存中的gzip文件流解压缩。这是参考资料 gzip filter

    ifstream file("hello.gz", ios_base::in | ios_base::binary);
    filtering_streambuf<input> in;
    in.push(gzip_decompressor());
    in.push(file);
    boost::iostreams::copy(in, cout);
    

    编辑:实际上这里有一个更好的代码段 https://stackoverflow.com/a/16693807/3656081

        2
  •  0
  •   tangy    5 年前

    有两种方法可以使用 zlib :

    1. Coliru Link -了解更多信息 here
    int inf(FILE* fp) {
        auto gzf = ::gzdopen(fileno(fp), "r");
        assert(::gztell(gzf) == 0);
        std::cout << "pos: " << ::gztell(gzf) << std::endl;
        ::gzseek(gzf, 18L, SEEK_SET);
        char buf[768] = {0};
        ::gzread(gzf, buf, sizeof(buf)); // use a custom size as needed
        std::cout << buf << std::endl; // Print file contents from 18th char onward
        ::gzclose(gzf);
        return 0;
    }
    
    1. 本地人 inflate 应用程序编程接口: Coliru Link . 更多关于这方面的信息,请参见上面的手册链接 here . 我的代码几乎完全是一个提供的链接和相当长的副本,所以我不会重新发布。