c++ - 用于压缩的缓冲区的 zlib c++ char 大小

标签 c++ char zlib

我正在使用此函数进行 zlib 压缩,并想知道是否应将 outbuffer 变量设置为特定大小?它是否将 char 数组限制为我在此处放置的任何内容?我可以放在这里的长度有限制吗?将它转换为 std::string 是否有意义,因为我是用 C++ 编译的?

 /** Compress a STL string using zlib with given compression level and return
     * the binary data. */
    std::string compress_string(const std::string& str, int compressionlevel = 9)
    {
        z_stream zs;                        // z_stream is zlib's control structure
        memset(&zs, 0, sizeof(zs));

        if (deflateInit(&zs, compressionlevel) != Z_OK)
            throw(std::runtime_error("deflateInit failed while compressing."));

        // For the compress
        deflateInit2(&zs, compressionlevel, Z_DEFLATED,MOD_GZIP_ZLIB_WINDOWSIZE + 16,MOD_GZIP_ZLIB_CFACTOR,Z_DEFAULT_STRATEGY) != Z_OK;

        zs.next_in = (Bytef*)str.data();
        zs.avail_in = str.size();           // set the z_stream's input

        int ret;
        char outbuffer[3222768];
        std::string outstring;

        // retrieve the compressed bytes blockwise
        do {
            zs.next_out = reinterpret_cast<Bytef*>(outbuffer);
            zs.avail_out = sizeof(outbuffer);

            ret = deflate(&zs, Z_FINISH);

            if (outstring.size() < zs.total_out) {
                // append the block to the output string
                outstring.append(outbuffer,zs.total_out - outstring.size());
            }
        }
        while (ret == Z_OK);

        deflateEnd(&zs);

        if (ret != Z_STREAM_END) {          // an error occurred that was not EOF
            std::ostringstream oss;
            oss << "Exception during zlib compression: (" << ret << ") " << zs.msg;
            throw(std::runtime_error(oss.str()));
        }

        return outstring;
    }

最佳答案

这就是 deflateBound() 的用途。在您的 deflateInit2() 之后,您可以使用输入大小调用它,它会在压缩不可压缩数据时限制可能的扩展。

顺便说一句,在同一个结构上调用两次deflateInit/deflateInit2 会导致大量内存泄漏。只需调用其中之一即可。

您应该阅读 zlib documentation完整的。

关于c++ - 用于压缩的缓冲区的 zlib c++ char 大小,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39568929/

相关文章:

c++ - 通过非静态成员函数转换 vector

c++ - 如何为回收站添加上下文菜单

Node.js:从 s3 下载文件并将其解压缩为字符串

c++ - 使用 libzip 从 .zip 获取文件(文本除外)

c++ - 安装 thrift idl

c++ - 类模板 C++ 中的虚方法模板

c# - 与 char 变量相对的下一个字母

java - 将指针转换为字符串并作为字符数组发送无法正常工作

c# - 对于 'char' 变量,“int”从不等于 null

c++ - 使用 zlib 压缩 boost 二进制文件