zlib:inflate返回错误的avail_out?

时间:2015-01-15 15:04:16

标签: c zlib

我想使用inflate()解压缩缩小的缓冲区并将结果写入文件。 因此我使用了this example的代码。我还使用示例代码来缩小我的缓冲区,它可以正常工作。但是当我给我的数据充气时,输出大小似乎是错误的。我的文件输出具有正确膨胀的代码,但结尾填充'0xCC',直到写入CHUNK字节(16kB)。输入缓冲区的大小是<块。文件流设置为O_BINARY。内部循环运行两次,一次是strm.avail_out == 0然后是strm.avail_out == CHUNK。这意味着写入CHUNK字节,尽管输出的大小较小。

#define CHUNK 16384

byte chunkBuf[CHUNK];

int inf(byte *src, size_t srcsize, FILE *dest)
{
    int ret;
    unsigned have;
    unsigned char in[CHUNK];
    unsigned long srcpos = 0;
    z_stream strm;

    /* allocate inflate state */
    strm.zalloc = Z_NULL;
    strm.zfree = Z_NULL;
    strm.opaque = Z_NULL;
    strm.avail_in = 0;
    strm.next_in = Z_NULL;
    ret = inflateInit(&strm);
    if (ret != Z_OK) {
        printf("ERR: inf: %i\n",ret);
        return ret;
    }
    /* decompress until deflate stream ends or end of file */
    do {
        if (srcsize - srcpos > CHUNK) {
            memcpy(in,src+srcpos,CHUNK);
            strm.avail_in = CHUNK;
            srcpos += CHUNK;
        } else if (srcsize - srcpos > 0) {
            memcpy(in,src+srcpos,srcsize - srcpos);
            strm.avail_in = srcsize - srcpos;
            srcpos = srcsize;
        } else {
            break;
        }

        strm.next_in = in;

        /* run inflate() on input until output buffer not full */
        do {
            strm.avail_out = CHUNK;
            strm.next_out = chunkBuf;
            ret = inflate(&strm, Z_NO_FLUSH);
            assert(ret != Z_STREAM_ERROR);  /* state not clobbered */
            switch (ret) {
            case Z_NEED_DICT:
                ret = Z_DATA_ERROR;     /* and fall through */
            case Z_DATA_ERROR:
            case Z_MEM_ERROR:
                (void)inflateEnd(&strm);
                return ret;
            }

            have = CHUNK - strm.avail_out;
            if (fwrite(chunkBuf, 1, have, dest) != have || ferror(dest)) {
                (void)inflateEnd(&strm);
                return Z_ERRNO;
            }
        } while (strm.avail_out == 0);

        /* done when inflate() says it's done */
    } while (ret != Z_STREAM_END);

    /* clean up and return */
    (void)inflateEnd(&strm);

    return ret == Z_STREAM_END ? Z_OK : Z_DATA_ERROR;
}

1 个答案:

答案 0 :(得分:1)

您可能在数据后给出了缩小和压缩垃圾的错误长度。