【问题标题】:uncompress error when using zlib使用 zlib 时解压缩错误
【发布时间】:2015-05-06 14:27:32
【问题描述】:

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

#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' 获得的。

谢谢!

【问题讨论】:

    标签: c zlib


    【解决方案1】:

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

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

    【讨论】:

    • 谢谢你,@Wumpus Q. Wumbley。想知道是否可以使用 zlib 解压缩 gzip 压缩的内容。
    【解决方案2】:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-01-22
      • 2023-04-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多