Skip to content

Instantly share code, notes, and snippets.

@w32zhong
Created July 7, 2016 06:39
Show Gist options
  • Save w32zhong/a0fb43cfd59c54f2a1099a135a9d378b to your computer and use it in GitHub Desktop.
Save w32zhong/a0fb43cfd59c54f2a1099a135a9d378b to your computer and use it in GitHub Desktop.
simple zlib string compress/decompress example
/* compile with:
* gcc simple-zlib.c -lz
*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <zlib.h>
#undef N_DEBUG
#include <assert.h>
int main()
{
char src[] = "The initialization of the state is the same, except that there is no compression level, of course, and two more elements of the structure are initialized. avail_in and next_in must be initialized before calling inflateInit(). This is because the application has the option to provide the start of the zlib stream in order for inflateInit() to have access to information about the compression method to aid in memory allocation. In the current implementation of zlib (up through versions 1.2.x), the method-dependent memory allocations are deferred to the first call of inflate() anyway. However those fields must be initialized since later versions of zlib that provide more compression methods may take advantage of this interface. In any case, no decompression is performed by inflateInit(), so the avail_out and next_out fields do not need to be initialized before calling.";
long unsigned int src_len = strlen(src) + 1;
long unsigned int dest_len = compressBound(src_len);
char *dest = malloc(dest_len);
printf("buffer len=%lu\n", dest_len);
/* compress */
assert(compress(dest, &dest_len, src, src_len) == Z_OK);
printf("orgin len=%lu\n", src_len);
printf("after compress, len=%lu\n", dest_len);
/* decompress */
src_len = sizeof(src);
memset(src, 0, sizeof(src));
assert(uncompress(src, &src_len, dest, dest_len) == Z_OK);
printf("after decompress, len=%lu\n", src_len);
free(dest);
printf("%s\n", src);
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment