我做了一个简单的函数,它接受一个 gzip 文件,然后提取到某个地方。出于测试目的,我使用了一个文本文件,该文件已通过通用实用程序 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");
}
最佳答案
您应该使用inflate()
,而不是uncompress()
。在 inflateInit2()
中,您可以指定 gzip 格式(或自动检测 zlib 或 gzip 格式)。请参阅 zlib.h 中的文档。
您可以在 zlib 中获取 uncompress()
的源代码,并进行简单的更改以使用 inflateInit2()
而不是 inflateInit()
创建您自己的 gzipuncompress()
,或者您喜欢的任何名称。
关于c++ - 'zlib' 的 Uncompress() 返回 Z_DATA_ERROR,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22809458/