Zlib (http://zlib.net/) provides a simple and efficient in-memory data compression and decompression series of API functions, many applications will use this library, among them, compress and uncompress functions are the most basic and commonly used. However, although compress and uncompress functions are already very simple, they are still difficult to use. In fact, the final result is that some things are not clear, let's take a look at the following code.
# Include <stdlib. h> # include <string. h> # include <stdio. h> # include <zlib. h> int main (INT argc, char * argv []) {char text [] = "zlib compress and uncompress test \ nturingo@163.com \ n2012-11-05 \ n "; ulong tlen = strlen (text) + 1;/* the string Terminator '\ 0' must also be processed */char * Buf = NULL; ulong blen; /* calculate the buffer size and allocate the memory */blen = compressbound (tlen ); /* the compressed length cannot exceed blen */If (BUF = (char *) malloc (sizeof (char) * blen) = NULL) {printf ("No enough memory! \ N "); Return-1;}/* compression */If (compress (BUF, & blen, text, tlen )! = Z_ OK) {printf ("compress failed! \ N "); Return-1;}/* decompress */If (uncompress (text, & tlen, Buf, blen )! = Z_ OK) {printf ("uncompress failed! \ N "); Return-1;}/* print the result and release the memory */printf (" % s ", text); If (BUF! = NULL) {free (BUF); Buf = NULL;} return 0 ;}
The object processed by zlib is bytef * byte stream. Many people will confuse the string. In fact, it is very simple. The byte stream has no Terminator and requires length information, therefore, when processing a string, you need to regard the Terminator as a common byte. In this way, you also need to calculate its length. In addition, most people want to dynamically allocate the buffer, that is, how much to give again. In fact, zlib itself provides the compressbound function to calculate the upper limit of the buffer length after compression, there is no need to design some inappropriate prediction algorithms, but the length prediction is not provided during decompression. Since compress and uncompress are generally used in pairs, you can save the length of the original text in advance.