How can I easily compress and decompress files using zlib?

Datoxalas picture Datoxalas · Apr 13, 2011 · Viewed 25.3k times · Source

How can I easily compress and decompress files using zlib?

Answer

Cristi picture Cristi · Apr 13, 2011

For decompression:

char buf[1024*1024*16];
gzFile *fi = (gzFile *)gzopen("file.gz","rb");
gzrewind(fi);
while(!gzeof(fi))
{
    int len = gzread(fi,buf,sizeof(buf));
        //buf contains len bytes of decompressed data
}
gzclose(fi);

For compression

gzFile *fi = (gzFile *)gzopen("file.gz","wb");
gzwrite(fi,"my decompressed data",strlen("my decompressed data"));
gzclose(fi);