【问题标题】:Gzip a string in Zlib using C/C++使用 C/C++ 在 Zlib 中压缩字符串
【发布时间】:2014-02-19 07:47:47
【问题描述】:

我想使用 C++(或 C)中的 gzip 来 gzip 字符串。如果可能,我想使用 zlib。

当我得知我必须使用 zlib 进行压缩和解压缩时,我在 Google 上搜索了几分钟,然后快速编写了一个程序来 gzip 文件然后解压缩它。但是,我实际上没有必要这样做。我需要使用 gzip 来压缩和解压缩字符串,而不是文件。我找不到太多关于在字符串上使用 gzip 的好文档。我发现的每个示例都适用于文件。

谁能给我一个简单的例子?

提前致谢。

【问题讨论】:

  • 如果您查看zlib usage examples,他们会创建函数来对文件进行充气和放气。但是这些函数手动从文件中读取数据。您不是从文件中读取数据,而是从字符串中读取。另请阅读zlib manual

标签: gzipstream gzip gzipinputstream gzipoutputstream


【解决方案1】:

它内置在 Poco 中(C++ 库/框架、许多实用程序、网络、您所拥有的)。这是一个示例程序:

#include <iostream>
#include <sstream>
#include <Poco/InflatingStream.h>
#include <Poco/DeflatingStream.h>
#include <Poco/StreamCopier.h>

int main() {

    std::ostringstream stream1;
    Poco::DeflatingOutputStream
      gzipper(stream1, Poco::DeflatingStreamBuf::STREAM_GZIP);
    gzipper << "Hello World!";
    gzipper.close();
    std::string zipped_string = stream1.str();
    std::cout << "zipped_string: [" << zipped_string << "]\n";

    std::ostringstream stream2;
    Poco::InflatingOutputStream
      gunzipper(stream2, Poco::InflatingStreamBuf::STREAM_GZIP);
    gunzipper << zipped_string;
    gunzipper.close();
    std::string unzipped_string = stream2.str();
    std::cout << "unzipped_string back: [" << unzipped_string << "]\n";

    return 0;
}

好消息是,您可以将 Poco gzipping 流连接到文件等,而不是上面的 ostringstreams。

【讨论】:

  • 嗨,我想知道是否还有一种方法可以使用直接进入驻留在现有 zip 存档中的文件的流。你知道这是否可以做到吗?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-11-12
  • 1970-01-01
相关资源
最近更新 更多