本文介绍利用zlib实现对GZip文件的解压缩:
CString sFullFileName = "D:\\test.gzip";
int nPos = sFullFileName.ReverseFind('\\');
FILE* fp;
errno_t err; //错误变量的定义
err = _tfopen_s(&fp, sFullFileName, _T("r+b"));
if (err) return;
fseek(fp, 0L, SEEK_END);
long ufileLength = ftell(fp);
fseek(fp, 0L, SEEK_SET);
unsigned char head[16];
fread(head, sizeof(head), 1, fp);
fclose(fp);
// 判断文件压缩类型是否是GZIP
/*
+------ + ------ + ------ + ------ - +-- - +-- - +-- - +-- - +------ + ---- - +
| ID1 | ID2 | CM | FLG | MTIME | XFL | OS |
+------ + ------ + ------ + ------ - +-- - +-- - +-- - +-- - +------ + ---- - +
// 详细见:https://blog.youkuaiyun.com/jison_r_wang/article/details/52068607
1、文件以10字节的定长部分开始,前2字节 0x1F 0x8B
2、 头部扩展字段
按照顺序依次是:FEXTRA+FNAME+FCOMMENT+FHCRC
*/
if (head[0] == 0x1F && head[1] == 0x8B)
{
#ifdef _UNICODE
gzFile gzfp = gzopen_w(sFullFileName.GetBuffer(0), ("rb"));
#else
gzFile gzfp = gzopen(sFullFileName.GetBuffer(0), ("rb"));
#endif
if (!gzfp) return;
CString sPath;
m_edtBrowse.GetWindowText(sPath);
if (sPath.IsEmpty())
sPath = ".\\";
CString sFileName = sFullFileName.Right(sFullFileName.GetLength() - nPos);
CString sOutFileName = sPath + sFileName;
err = _tfopen_s(&fp, sOutFileName, _T("wb"));
if (err)
{
gzclose(gzfp);
return;
}
unsigned char* buf = new unsigned char[GZ_READ_BUF_SIZE];
int have;
::std::string out;
while ((have = gzread(gzfp, buf, GZ_READ_BUF_SIZE)) > 0)
{
out.append((const char*)buf, have);
fwrite(buf, have, 1, fp);
}
fclose(fp);
gzclose(gzfp);
}
本文详细介绍使用zlib库解压GZip文件的过程,包括读取文件、判断压缩类型及解压缩步骤。通过实例演示了如何在不同编码环境下正确打开并处理GZip压缩文件。
2134

被折叠的 条评论
为什么被折叠?



