Posted on 2007-03-28 18:23 by Timo at Permlink with Comments. Tags: c++ code-snippet
The zlib library can be found on virtually every computer. It is THE general-purpose lossless patent-free compression library.
This small C++ code snippet features a pair of functions which use this ubiquitous library to compress ordinary STL strings. There are many uses for this code snippet, like compressing string data stored in a database or binary data transfered over a network. Keep in mind that the compressed string data is binary, so the string's c_str() representation must be avoided.
To compile the following small program use "gcc testzlib.cc -o testzlib -lz" where testzlib.cc is the code.
Comment by Timo at 2011-06-14 08:09 UTC - http://idlebox.net
Well, maybe you'd best check whether a std::string can contain "binary data".
Greetings, Timo
Comment by Patrick at 2011-06-17 06:46 UTC
Hi
I just tested this code in Mac OS X... I saved it as gzip.cpp and ran g++ -o gzip gzip.cpp, but I got the following error:
g++ -o gzip gzip.cpp
Undefined symbols:
"_inflateEnd", referenced from:
decompress_string(std::basic_string, std::allocator > const&)in ccT57o1k.o
"_deflateInit_", referenced from:
compress_string(std::basic_string, std::allocator > const&, int)in ccT57o1k.o
"_inflate", referenced from:
decompress_string(std::basic_string, std::allocator > const&)in ccT57o1k.o
"_deflateEnd", referenced from:
compress_string(std::basic_string, std::allocator > const&, int)in ccT57o1k.o
"_inflateInit_", referenced from:
decompress_string(std::basic_string, std::allocator > const&)in ccT57o1k.o
"_deflate", referenced from:
compress_string(std::basic_string, std::allocator > const&, int)in ccT57o1k.o
ld: symbol(s) not found
collect2: ld returned 1 exit status
How can I fix this, do you have any idea?
Comment by Timo at 2011-06-17 08:27 UTC - http://idlebox.net
Yes, just add -lz to the gcc line. Sorry about that. I've appended this tip to the blog post.
Timo
Comment by Sam Dutton at 2011-06-08 14:00 UTC - http://mailto:samdutton@gmail.com
Thanks for this.
I realise this post is four years old, but I'll comment anyway...
Excuse my ignorance of compression and encoding algorithms, but I'm looking for a way to compress a std::string, in a way that the 'compressed string' can be stored as a std::string, and later retrieved and decompressed to a std::string. Is this possible with your code?
I'm probably missing the point here, but the comment on compress_string() seems to conflict with the std::string return type:
/** Compress a STL string using zlib with given compression level and return
* the binary data. */