I am trying to implement the zlib.h deflate and inflate functions to compress and decompress a char array (not a file).
I would like to know if the following syntax is correct ? Am I missing something or defined something incorrectly ?
char a[50] = "Hello World!";
char b[50];
char c[50];
// deflate
// zlib struct
z_stream defstream;
defstream.zalloc = Z_NULL;
defstream.zfree = Z_NULL;
defstream.opaque = Z_NULL;
defstream.avail_in = (uInt)sizeof(a); // size of input
defstream.next_in = (Bytef *)a; // input char array
defstream.avail_out = (uInt)sizeof(b); // size of output
defstream.next_out = (Bytef *)b; // output char array
deflateInit(&defstream, Z_DEFAULT_COMPRESSION);
deflate(&defstream, Z_FINISH);
deflateEnd(&defstream);
printf("Deflate:\n%lu\n%s\n", strlen(b), b);
// inflate
// zlib struct
z_stream infstream;
infstream.zalloc = Z_NULL;
infstream.zfree = Z_NULL;
infstream.opaque = Z_NULL;
infstream.avail_in = (uInt)sizeof(b); // size of input
infstream.next_in = (Bytef *)b; // input char array
infstream.avail_out = (uInt)sizeof(c); // size of output
infstream.next_out = (Bytef *)c; // output char array
inflateInit(&infstream);
inflate(&infstream, Z_NO_FLUSH);
inflateEnd(&infstream);
printf("Inflate:\n%lu\n%s\n", strlen(c), c);
The deflate method encodes the input data into compressed data. The decompression algorithm used in zlib is the inflate method, which is the decoding process that takes a deflate bit stream for decompression and correctly produces the original full-size data or file.
Zlib:Inflate is the class for decompressing compressed data.
The 'zlib' compression library provides in-memory compression and. decompression functions, including integrity checks of the uncompressed data. This version of the library supports only one compression method (deflation) but other algorithms will be added later and will have the same stream. interface.
zlib already has a simple inflate/deflate function you can use.
char a[50] = "Hello, world!";
char b[50];
char c[50];
uLong ucompSize = strlen(a)+1; // "Hello, world!" + NULL delimiter.
uLong compSize = compressBound(ucompSize);
// Deflate
compress((Bytef *)b, &compSize, (Bytef *)a, ucompSize);
// Inflate
uncompress((Bytef *)c, &ucompSize, (Bytef *)b, compSize);
When in doubt, check out the zlib manual. My code is crappy, sorry =/
The zpipe example (http://zlib.net/zpipe.c) pretty much covers it, just remove the file ops(the f prefixed function), and you replace in
and out
with your in-memory buffers, though it may be enough to only replace in
or keep the buffers as-is depending on you usage. Just note that you will need to make your out buffer resizeable to account for decompression of arbitrarily sized data, if you are planning on having unknown sized chunks
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With