2015-05-06 137 views
1

這可能是一個愚蠢的問題。當我試圖解壓縮內存中的壓縮數據時,出現錯誤。這是代碼。使用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; 
} 

GOT錯誤:從由運行`gzip的te.html」獲得

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

te.html.gz。

謝謝!

回答

2

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

您可以通過編寫一個類似的程序來調用zlib中的compress函數來生成一些zlib格式的測試數據。或者你可以使用openssl zlib命令,如果你已經安裝了openssl。

+0

謝謝@Wumpus Q. Wumbley。不知道是否可以使用zlib解壓縮gzip內容。 – packetie

0

完整,致力於解壓縮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; 
}