Note that the comments section in the code, where the settings are specifically for gzip, is missing, the difference between gzip compression format and other formats is here.
Bytef is unsigned char,ulong is unsigned long, the settings of these aliases are in the Zconf.h file.
Here the compression and decompression of data can be used in Java Gzipinputstream and Gzipoutputstream to the corresponding decompression and compression.
Code slices#ifndef Gzip_h#define GZIP_H#include "zlib/zlib.h"/ * Compress gzip data * // * Data Original data ndata the original data length Zdata compressed after the nzdata compression length * /intGzcompress (Bytef *data, ulong ndata, Bytef *zdata, ulong *nzdata) {Z_stream c_stream;intErr =0;if(Data && ndata >0) {C_stream. Zalloc=NULL; C_stream. Zfree=NULL; C_stream. Opaque=NULL;//Only set to Max_wbits + 16 to have headers and trailer in compressed text if(DeflateInit2 (&c_stream, Z_default_compression, z_deflated, Max_wbits + -,8, z_default_strategy)! = Z_OK)return-1; C_stream. next_in= data; C_stream. avail_in= Ndata; C_stream. Next_out= Zdata; C_stream. Avail_out= *nzdata; while(C_stream. avail_in!=0&& C_stream. Total_out< *nzdata) {if(Deflate (&c_stream, z_no_flush)! = Z_OK)return-1; }if(C_stream. avail_in!=0)returnC_stream. avail_in; for(;;) {if(Err = deflate (&c_stream, z_finish)) = = Z_stream_end) Break;if(Err! = Z_OK)return-1; }if(Deflateend (&c_stream)! = Z_OK)return-1; *nzdata = C_stream. Total_out;return 0; }return-1;}/ * uncompress gzip data * // * Zdata Data nzdata The original data length data extracted after ndata decompression length * /intGzdecompress (Byte *zdata, ulong Nzdata, byte *data, ulong *ndata) {intErr =0; Z_stream D_stream = {0};/ * Decompression stream * / Static Chardummy_head[2] = {0x8+0x7*0x10, (((0x8+0x7*0x10) *0x100+ -) / to* to) &0xFF, }; D_stream. Zalloc=NULL; D_stream. Zfree=NULL; D_stream. Opaque=NULL; D_stream. next_in= Zdata; D_stream. avail_in=0; D_stream. Next_out= data;//Only set to Max_wbits + 16 to decompress text with header and trailer if(InflateInit2 (&d_stream, Max_wbits + -)! = Z_OK)return-1;//if (InflateInit2 (&d_stream, a)! = Z_OK) return-1; while(D_stream. Total_out< *ndata && D_stream. total_in< Nzdata) {D_stream. avail_in= D_stream. Avail_out=1;/ * Force Small buffers * / if(Err = Inflate (&d_stream, z_no_flush)) = = Z_stream_end) Break;if(Err! = Z_OK) {if(Err = = Z_data_error) {D_stream. next_in= (bytef*) dummy_head; D_stream. avail_in=sizeof(Dummy_head);if(Err = Inflate (&d_stream, z_no_flush))! = Z_OK) {return-1; } }Else return-1; } }if(Inflateend (&d_stream)! = Z_OK)return-1; *ndata = D_stream. Total_out;return 0;}#endif//Gzip_h
Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.
Compression and decompression of gzip-formatted data using zlib