我做了一个简单的函数,它需要一个 gzipped 文件,并在某处提取。出于测试目的,我使用了一个通过通用实用程序gzip压缩的文本文件。但出于某种原因,Uncompress ()返回错误Z_DATA_ERROR。
我走进调试器直到函数,它肯定会得到正确的数据(整个文件内容,它只有 37 个字节),所以它似乎是两个之一:可怕的 zlib-bug 现在正在窃取你的时间,或者我错过了一些重要的东西,然后我真的很抱歉。
#include <zlib.h>
#include <cstdio>
int UngzipFile(FILE* Dest, FILE* Source){
#define IN_SIZE 256
#define OUT_SIZE 2048
bool EOFReached=false;
Bytef in[IN_SIZE];
Bytef out[OUT_SIZE];
while(!EOFReached){//for no eof
uLong In_ReadCnt = fread(in,1,IN_SIZE,Source);//read a bytes from a file to input buffer
if(In_ReadCnt!=IN_SIZE){
if(!feof(Source) ){
perror("ERR");
return 0;
}
else EOFReached=true;
}
uLong OutReadCnt = OUT_SIZE;//upon exit 'uncompress' this will have actual uncompressed size
int err = uncompress(out, &OutReadCnt, in, In_ReadCnt);//uncompress the bytes to output
if(err!=Z_OK){
printf("An error ocurred in GZIP, errcode is %i\n", err);
return 0;
}
if(fwrite(out,1,OutReadCnt,Dest)!=OUT_SIZE ){//write to a 'Dest' file
perror("ERR");
return 0;
}
}
return 1;
}
int main(int argc, char** argv) {
FILE* In = fopen("/tmp/Kawabunga.gz", "r+b");
FILE* Out = fopen("/tmp/PureKawabunga", "w+b");
if(!In || !Out){
perror("");
return 1;
}
if(!UngzipFile(Out,In))printf("An error encountered\n");
}
Run Code Online (Sandbox Code Playgroud)
您应该使用inflate(),而不是uncompress()。在 中inflateInit2(),您可以指定 gzip 格式(或自动检测 zlib 或 gzip 格式)。请参阅 zlib.h 中的文档。
您可以uncompress()在 zlib 中获取源代码并进行简单的更改以使用inflateInit2()而不是inflateInit()创建您自己的gzipuncompress().