简体   繁体   中英

C/C++ Arbitrary output size when decompressing GZIP

I'm using this to decompress a GZIP compressed file "input.gz" into the uncompressed "output.file". It works wonderfully, except I need a fixed size for the buffer (in this case 1MB) and if the output becomes larger the bytes get cut off. Is there a way to get this to work with any output size?

#include "zlib.h"
#include <stdio.h>

int main()
{
    char buf[1024*1024];

    gzFile in = gzopen("input.gz","rb8");
    int len = gzread(in,buf,sizeof(buf));
    gzclose(in);

    FILE* out = fopen("output.file", "wb");
    fwrite(buf,1,len,out);
    fclose(out);

    free(buf);
    return 0;
}

gzread works the same way as fread . Consecutive calls to gzread just read more data from that file. I haven't tested the code, but this should work fine.

#include "zlib.h"
#include <stdio.h>

int main() {
    char buf[1024];
    gzFile in = gzopen("input.gz","rb8");
    FILE* out = fopen("output.file", "wb");
    while (int len = gzread(in, buf, sizeof(buf)))
        fwrite(buf, 1, len, out);
    gzclose(in);
    fclose(out);
    return 0;
}

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