使用zlib解压报错

uncompress error when using zlib

这可能是个愚蠢的问题。当我试图解压缩内存中的压缩数据时,出现错误。这是代码。

#include <zlib.h>
#include <stdio.h>
#include <stdlib.h>

int readFile(char *fname, char buf[]) {
    FILE *fp = fopen(fname, "rb");
    if (fp == NULL) { printf("Failed to open %s\n", fname); exit(0);}
    int n = fread(buf, 1, 0x100000, fp);
    fclose(fp);
    return n;
}

char buf[2][0x10000];
int main(int argc, char *argv[]) {
    long n = readFile(argv[1], &buf[0][0]);
    unsigned int *pInt = (unsigned int*) (&buf[0][0]);
    printf("n=%d %08x\n", n, *pInt);
    long m = 0x10000;
    int rc = uncompress(&buf[1][0], &m, &buf[0][0], n);
    printf("rc = %d %s\n", rc, &buf[1][0]);
    return 0;
}

出现错误:

./a.out te.html.gz
n=169 08088b1f
rc = -3 

te.html.gz 是通过 运行 `gzip te.html' 获得的。

谢谢!

zlib 格式不是 gzip 格式。 zlib uncompress 函数不理解 gzip 格式。

你可以编写一个类似的程序调用zlib中的compress函数来生成一些zlib格式的测试数据。或者你可以使用 openssl zlib 命令,如果你安装了 openssl。

关于解压缩 gzip 数据的完整的工作示例(感谢 link

#include <zlib.h>
#include <stdio.h>
#include <stdlib.h>

int readFile(char *fname, char buf[]) {
    FILE *fp = fopen(fname, "rb");
    if (fp == NULL) { printf("Failed to open %s\n", fname); exit(0);}
    int n = fread(buf, 1, 0x100000, fp);
    fclose(fp);
    return n;
}
int inf(const char *src, int srcLen, const char *dst, int dstLen){
    z_stream strm;
    strm.zalloc=NULL;
    strm.zfree=NULL;
    strm.opaque=NULL;

    strm.avail_in = srcLen;
    strm.avail_out = dstLen;
    strm.next_in = (Bytef *)src;
    strm.next_out = (Bytef *)dst;

    int err=-1, ret=-1;
    err = inflateInit2(&strm, MAX_WBITS+16);
    if (err == Z_OK){
        err = inflate(&strm, Z_FINISH);
        if (err == Z_STREAM_END){
            ret = strm.total_out;
        }
        else{
            inflateEnd(&strm);
            return err;
        }
    }
    else{
        inflateEnd(&strm);
        return err;
    }
    inflateEnd(&strm);
    printf("%s\n", dst);
    return err;
}


char buf[2][0x10000];
int main(int argc, char *argv[]) {
    long n = readFile(argv[1], &buf[0][0]);
    unsigned int *pInt = (unsigned int*) (&buf[0][0]);
    printf("n=%d %08x\n", n, *pInt);
    long m = 0x10000;
    int rc = inf(&buf[0][0], n, &buf[1][0], m);
    printf("rc = %d %s\n", rc, &buf[1][0]);
    return 0;
}