简体   繁体   English

将zlib用于std :: string和stringstream

[英]Using zlib for std::string and stringstream

I am using zlib for deflating string on the client side and inflating on the server side. 我正在使用zlib在客户端压缩字符串并在服务器端膨胀。

I found a link which does exactly this using char buffers: https://gist.github.com/arq5x/5315739 我发现了一个使用char缓冲区完全可以做到这一点的链接: https : //gist.github.com/arq5x/5315739

Can someone post simple examples using zlib methods for std::string and std::stringstream for doing the same? 有人可以为std::stringstd::stringstream使用zlib方法发布简单的示例吗?

EDIT : Please don't use Boost , as I am developing a restricted API. 编辑 :请不要使用Boost ,因为我正在开发受限的API。

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. 因此,我从下载的zlib随附的zlib.h文档和examples.c中发现,只能使用文件或char缓冲区进行压缩。 So, convert string or stringstreams to char buffers. 因此,将字符串或字符串流转换为char缓冲区。

Here is the code: https://panthema.net/2007/0328-ZLibString.html 这是代码: https : //panthema.net/2007/0328-ZLibString.html

I found an example online which is very useful, which works for me: 我在网上找到了一个非常有用的示例,对我有用:

blog: Compression of Simulation Data using ZLib 博客:使用ZLib压缩仿真数据

Bascially, using gzwrite and gzread for writing and reading just like writing regular files. 基本上,使用gzwrite和gzread进行写入和读取就像编写常规文件一样。 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 :: string obj,然后可以将字符串obj转换为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. 对于编写,将ostringstream obj转换为std :: string obj以包装为函数也可能更为灵活。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM