【问题标题】:Using zlib for std::string and stringstream将 zlib 用于 std::string 和 stringstream
【发布时间】:2015-09-09 05:34:07
【问题描述】:

我正在使用zlib 在客户端对字符串进行放气并在服务器端进行充气。

我找到了一个使用char 缓冲区的链接: https://gist.github.com/arq5x/5315739

有人可以为std::stringstd::stringstream 发布使用zlib 方法的简单示例吗?

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

【问题讨论】:

  • 您可以从带有data()c_str()std::string 获取char 缓冲区,您可以从带有str()std::stringstream 获取std::string。相反,您可以从char 缓冲区构造std::string,从std::string 构造std::stringstream
  • 我知道。刚从zlib头中发现,没有直接处理字符串或者stringstreams的方法

标签: c++ zlib stringstream stdstring deflate


【解决方案1】:

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

代码如下: https://panthema.net/2007/0328-ZLibString.html

【讨论】:

    【解决方案2】:

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

    blog: Compression of Simulation Data using ZLib

    基本上,使用 gzwrite 和 gzread 进行写入和读取就像写入常规文件一样。写的时候先写字符串大小,再写字符串。阅读顺序相同。读的时候先读入一个std::string obj,然后就可以把string obj转成istringstream了:

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

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

    【讨论】:

      猜你喜欢
      • 2018-12-03
      • 2013-01-22
      • 2016-09-10
      • 1970-01-01
      • 2011-01-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-10-19
      相关资源
      最近更新 更多