zlib can essentially write formatted gzip data to a buffer in memory.
This zlib faq entry sends comments to zlib.h. In the comment header file for deflateInit2 () it is mentioned that you must (optionally?) Add 16 to the 4th parameter (windowBits) to force the library to format the deflation stream using the gzip format (instead of the default "zlib" ").
This code gets the correct zlib state to encode gzip to the buffer:
#include <zlib.h> z_stream stream; stream.zalloc = Z_NULL; stream.zfree = Z_NULL; stream.opaque = Z_NULL; int level = Z_DEFAULT_COMPRESSION; int method = Z_DEFLATED; /* mandatory */ int windowBits = 15 + 16; /* 15 is default as if deflateInit */ /* were used, add 16 to enable gzip format */ int memLevel = 8; /* default */ int strategy = Z_DEFAULT_STRATEGY; if(deflateInit2(&stream, level, method, windowBits, memLevel, strategy) != Z_OK) { fprintf(stderr, "deflateInit failed\n"); exit(EXIT_FAILURE); } /* now use the deflate function as usual to gzip compress */ /* from one buffer to another. */
I have confirmed that this procedure gives the same binary output as the gzopen / gzwrite / gzclose interface.
source share