使用zlib时解压缩错误

时间:2015-05-06 14:27:33

标签: c 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'获得的。

谢谢!

2 个答案:

答案 0 :(得分:3)

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

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

答案 1 :(得分:1)

关于解压缩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;
}