gpt4 book ai didi

c++ - zlib deflateInit 总是返回 Z_STREAM_ERROR

转载 作者:行者123 更新时间:2023-11-28 05:14:44 28 4
gpt4 key购买 nike

我正在使用来自 https://panthema.net/2007/0328-ZLibString.html 的片段压缩字符串。我的问题是 deflateInit() 总是返回 Z_STREAM_ERROR。

根据zlib manual ,这意味着压缩级别错误。

deflateInit returns Z_OK if success, Z_MEM_ERROR if there was not enough memory, Z_STREAM_ERROR if level is not a valid compression level

根据手册,正确的压缩级别是 0-9 之间的值。

The compression level must be Z_DEFAULT_COMPRESSION, or between 0 and 9: 1 gives best speed, 9 gives best compression, 0 gives no compression at all (the input data is simply copied a block at a time). Z_DEFAULT_COMPRESSION requests a default compromise between speed and compression (currently equivalent to level 6).

但无论我为压缩设置什么值,它总是返回 -2(Z_STREAM_ERROR)

#include <string>
#include <stdexcept>
#include <iostream>
#include <iomanip>
#include <sstream>

#include "zlib.h"

std::string compress_string(const std::string& str, int compressionlevel)
{
z_stream zs; // z_stream is zlib's control structure
memset(&zs, 0, sizeof(zs));

//std::cout << deflateInit(&zs, 9); //Always returns -2, no matter if the value is between 0-9
if (deflateInit(&zs, compressionlevel) != Z_OK)
throw(std::runtime_error("deflateInit failed while compressing."));

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

int ret;
char outbuffer[32768];
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;
}

我正在使用从 Windows GnuWin32 安装程序获得的 zlib 1.2.3。我在 zconf.h 中进行了更改并注释掉了 #if 1 并改为放置了 #if HAVE_UNISTD_H 因为我不在 Linux 上并且做没有 unistd.h

看起来像

//#if 1           /* HAVE_UNISTD_H -- this line is updated by ./configure */
#if HAVE_UNISTD_H
# include <sys/types.h> /* for off_t */
# include <unistd.h> /* for SEEK_* and off_t */

额外说明:我没有定义Z_SOLO

最佳答案

只有两种方法可以从deflateInit() 获取Z_STREAM_ERROR。如果第一个参数为 NULL,或者如果第二个参数不在 -1..9 范围内,它们是。通过检查和您对传递的压缩级别的声明,您的代码似乎没有违反任何一个条件。

我唯一的猜测是你的 zlib 编译和链接在某处搞砸了,传递的类型与例程所期望的不匹配,导致例程接收到的级别与你发送的级别不同。

关于c++ - zlib deflateInit 总是返回 Z_STREAM_ERROR,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42893519/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com