繁体   English   中英

zlib deflateInit始终返回Z_STREAM_ERROR

[英]zlib deflateInit always returns Z_STREAM_ERROR

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

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

deflateInit如果成功则返回Z_OK,如果内存不足则返回Z_MEM_ERROR,如果level不是有效的压缩级别则返回Z_STREAM_ERROR

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

压缩级别必须为Z_DEFAULT_COMPRESSION,或者在0到9之间:1给出最佳速度,9给出最佳压缩,0根本不压缩(输入数据一次仅复制一个块)。 Z_DEFAULT_COMPRESSION请求在速度和压缩之间进行默认折衷(当前等效于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范围内,则为true。 通过检查和您对传递的compressionLevel的声明,似乎您的代码不会违反任何一种条件。

我唯一可以冒险的猜测是,您的zlib的编译和链接在某个地方弄乱了,并且传递的类型与例程所期望的不匹配,从而导致例程接收的级别与您发送的级别不同。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM