C - 如何gzip将文件块解压缩到内存缓冲区

时间:2014-07-14 14:43:39

标签: c++ c gzip

我有一个C函数将gzip文件解压缩到另一个文件中:

bool gzip_uncompress(const std::string &compressed_file_path,std::string &uncompressed_file_path)
{
    char outbuffer[1024*16];
    gzFile infile = (gzFile)gzopen(compressed_file_path.c_str(), "rb");
    FILE *outfile = fopen(uncompressed_file_path.c_str(), "wb");
    gzrewind(infile);
    while(!gzeof(infile))
    {
        int len = gzread(infile, outbuffer, sizeof(outbuffer));
        fwrite(outbuffer, 1, len, outfile);
    }
    fclose(outfile);
    gzclose(infile);
    return true;
}

这很有效。

但是,我想将解压缩的缓冲区块写入新的char[]而不是输出文件。但我不知道如何确定完整解压缩文件的长度,以便声明char[?]缓冲区来保存完整输出。

是否可以修改上述功能以将文件解压缩到内存中?我认为我将其解压缩为char[],但也许vector<char>是更好?有关系吗?使用CC++对我有效。

1 个答案:

答案 0 :(得分:3)

这在C ++中很简单:

vector<char> gzip_uncompress(const std::string &compressed_file_path)
{
    char outbuffer[1024*16];
    gzFile infile = (gzFile)gzopen(compressed_file_path.c_str(), "rb");
    vector<char> outfile;
    gzrewind(infile);
    while(!gzeof(infile))
    {
        int len = gzread(infile, outbuffer, sizeof(outbuffer));
        outfile.insert(outfile.end(), outbuffer, outbuffer+len);
    }
    gzclose(infile);
    return outfile;
}

您也可以完全省略outbuffer,而是在每次读取之前调整向量大小,并直接读取调整大小添加的字节,这样可以避免复制。

C版需要使用mallocrealloc