Using zlib for std::string and stringstream

3.3k views Asked by At

I am using zlib for deflating string on the client side and inflating on the server side.

I found a link which does exactly this using char buffers: https://gist.github.com/arq5x/5315739

Can someone post simple examples using zlib methods for std::string and std::stringstream for doing the same?

EDIT: Please don't use Boost, as I am developing a restricted API.

2

There are 2 answers

0
V Shreyas On BEST ANSWER

So, I found out from zlib.h documentation and examples.c which come with downloaded zlib, that you can only use files or char buffers for compression. So, convert string or stringstreams to char buffers.

Here is the code: https://panthema.net/2007/0328-ZLibString.html

0
Pengyao On

I found an example online which is very useful, which works for me:

blog: Compression of Simulation Data using ZLib

Bascially, using gzwrite and gzread for writing and reading just like writing regular files. When writing, first write the string size, then write the string. Same order for reading. When reading, first read into a std::string obj, and then you can convert string obj to istringstream:

std::istringstream in(data);  // data is std::string type, using the same notation as in the blog

For writing, it may also be more flexible to convert the ostringstream obj to std::string obj to wrap as function.