How to compress a buffer with zlib?

后端 未结 5 409
無奈伤痛
無奈伤痛 2020-12-23 13:15

There is a usage example at the zlib website: http://www.zlib.net/zlib_how.html

However in the example they are compressing a file. I would like to compress a binary

5条回答
  •  囚心锁ツ
    2020-12-23 13:32

    You can easily adapt the example by replacing fread() and fwrite() calls with direct pointers to your data. For zlib compression (referred to as deflate as you "take out all the air of your data") you allocate z_stream structure, call deflateInit() and then:

    1. fill next_in with the next chunk of data you want to compress
    2. set avail_in to the number of bytes available in next_in
    3. set next_out to where the compressed data should be written which should usually be a pointer inside your buffer that advances as you go along
    4. set avail_out to the number of bytes available in next_out
    5. call deflate
    6. repeat steps 3-5 until avail_out is non-zero (i.e. there's more room in the output buffer than zlib needs - no more data to write)
    7. repeat steps 1-6 while you have data to compress

    Eventually you call deflateEnd() and you're done.

    You're basically feeding it chunks of input and output until you're out of input and it is out of output.

提交回复
热议问题