简体   繁体   中英

C - How can I gzip decompress chunks of a file into a memory buffer

I have a C function that is decompressing a gzip file into another file:

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;
}

And this works well.

However, I would like to write the decompressed buffer chunks to a new char[] instead of an output file. But I don't know how to determine the length of the full decompressed file in order to declare a char[?] buffer to hold the full output.

Is it possible to modify the above function to decompress a file into memory? I assumed I'd decompress it into a char[] , but maybe vector<char> is better? Does it matter? Either using C or C++ works for me.

This is straightforward in 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;
}

You can also dispense with outbuffer entirely, and instead resize the vector before each read and read directly into the bytes added by the resizing, which would avoid the copying.

The C version would need to use malloc and realloc .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM