Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ZLib Decompression in C++

I am trying to get a function going to unzip a single text file compressed with .gz. It needs to uncompress the .gz file given its path and write the uncompressed text file given its destination. I am using C++ and what I have seen is that ZLIB does exactly what I need except I cannot find 1 single example anywhere on the net that shows it doing this. Can anyone show me an example or at least guide me in the right direction?

like image 362
RobNHood Avatar asked Jun 12 '13 03:06

RobNHood


2 Answers

If you just want to inflate a file with raw deflated data (i.e. no archive) you can use something like this:

gzFile inFileZ = gzopen(fileName, "rb");
if (inFileZ == NULL) {
    printf("Error: Failed to gzopen %s\n", filename);
    exit(0);
}
unsigned char unzipBuffer[8192];
unsigned int unzippedBytes;
std::vector<unsigned char> unzippedData;
while (true) {
    unzippedBytes = gzread(inFileZ, unzipBuffer, 8192);
    if (unzippedBytes > 0) {
        unzippedData.insert(unzippedData.end(), unzipBuffer, unzipBuffer + unzippedBytes);
    } else {
        break;
    }
}
gzclose(inFileZ);

The unzippedData vector now holds your inflated data. There are probably more efficient ways to store the inflated data, especially if you know the uncompressed size in advance, but this approach works for me.
If you only want to save the inflated data to a file without any further processing you could skip the vector and just write the unzipBuffer contents to another file.

like image 172
Michael Avatar answered Sep 19 '22 07:09

Michael


You can use the gzopen(), gzread(), and gzclose() functions of zlib, much like you would the corresponding stdio functions fopen(), etc. That will read the gzip file and decompress it. You can then use fopen(), fwrite(), etc. to write the uncompressed data back out.

like image 33
Mark Adler Avatar answered Sep 20 '22 07:09

Mark Adler