我试图通过调用 inflate 函数来解压缩文件,但即使我使用网站上的示例程序,它也总是失败并出现 Z_DATA_ERROR 。我想也许我的 zip 文件不受支持。我在下面附上了 zip 标题的图片。
这是我编写的用于执行解压缩的函数。我一次读入整个文件(大约 34KB)并将其传递给这个函数。注意:我尝试过使用 zip 标头传递整个 zip 文件,以及跳过 zip 文件标头并仅传递压缩数据,当调用 inflate() 时,两者都会失败并出现 Z_DATA_ERROR。
int CHttpDownloader::unzip(unsigned char * pDest, unsigned long * ulDestLen, unsigned char * pSource, int iSourceLen){
int ret = 0;
unsigned int uiUncompressedBytes = 0; // Number of uncompressed bytes returned from inflate() function
unsigned char * pPositionDestBuffer = pDest; // Current position in dest buffer
unsigned char * pLastSource = &pSource[iSourceLen]; // Last position in source buffer
z_stream strm;
// Skip over local file header
SLocalFileHeader * header = (SLocalFileHeader *) pSource;
pSource += sizeof(SLocalFileHeader) + header->sFileNameLen + header->sExtraFieldLen;
// We should now be at the beginning of the stream data
/* allocate inflate state */
strm.zalloc = Z_NULL;
strm.zfree = Z_NULL;
strm.opaque = Z_NULL;
strm.avail_in = 0;
strm.next_in = Z_NULL;
ret = inflateInit2(&strm, 16+MAX_WBITS);
if (ret != Z_OK){
return -1;
}
// Uncompress the data
strm.avail_in = header->iCompressedSize; //iSourceLen;
strm.next_in = pSource;
do {
strm.avail_out = *ulDestLen;
strm.next_out = pPositionDestBuffer;
ret = inflate(&strm, Z_NO_FLUSH);
assert(ret != Z_STREAM_ERROR); /* state not clobbered */
switch (ret) {
case Z_NEED_DICT:
ret = Z_DATA_ERROR; /* and fall through */
case Z_DATA_ERROR:
case Z_MEM_ERROR:
(void)inflateEnd(&strm);
return -2;
}
uiUncompressedBytes = *ulDestLen - strm.avail_out;
*ulDestLen -= uiUncompressedBytes; // ulDestSize holds number of free/empty bytes in buffer
pPositionDestBuffer += uiUncompressedBytes;
} while (strm.avail_out == 0);
// Close the decompression stream
inflateEnd(&strm);
ASSERT(ret == Z_STREAM_END);
return 0;
}
所以我的问题是,ZLib 的 inflate() 函数是否不支持我正在读取的 zip 文件类型?或者我的 CHttpDownloader::unzip() 函数有问题吗?谢谢你的帮助 :)
Inflate() 失败,因为它正在寻找不存在的 GZip 标头。如果您使用以下方式初始化流:
ret = inflateInit2(&strm, -MAX_WBITS);
传递负窗口位值可防止 inflate 检查 gzip 或 zlib 标头并按预期解压缩。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)