对std::string和stringstream使用zlib

Using zlib for std::string and stringstream

本文关键字:使用 zlib stringstream string std      更新时间:2023-10-16

我使用zlib在客户端收缩字符串,在服务器端膨胀字符串。

我发现了一个使用char缓冲区实现这一点的链接:https://gist.github.com/arq5x/5315739

有人能为std::stringstd::stringstream发布使用zlib方法进行相同操作的简单示例吗?

编辑:请不要使用Boost,因为我正在开发一个受限的API。

因此,我从下载的zlib附带的zlib.h文档和examples.c中发现,您只能使用文件或字符缓冲区进行压缩。因此,将字符串或字符串流转换为字符缓冲区。

这是代码:https://panthema.net/2007/0328-ZLibString.html

我在网上找到了一个非常有用的例子:

博客:使用ZLib 压缩模拟数据

基本上,使用gzwrite和gzread进行写和读操作就像编写常规文件一样。写入时,首先写入字符串大小,然后写入字符串。阅读顺序相同。读取时,首先读取std::string obj,然后可以将字符串obj转换为istringstream:

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

对于编写,将ostringstream obj转换为std::string obj以包装为函数也可能更灵活。