VC下minizip+ZLib 解压文件

来源:互联网 发布:飞控编程用什么语言 编辑:程序博客网 时间:2024/06/06 01:18

一、zlib开源库

zlib是应用最广泛的压缩与解压缩zip文件的免费开源库,提供了数据压缩与解压缩的函式库。

zlib中最关键的函数有以下两个:

(1)int compress(Bytef *dest, uLongf *destLen, const Bytef *source, uLong sourceLen);

 (2)int uncompress(Bytef *dest, uLongf *destLen, const Bytef *source, uLong sourceLen);

  其中,函数compress()用于将源缓冲区数据压缩到目的缓冲区,函数uncompress()用于将源缓冲区数据解压到目的缓冲区。

从这里可以看出zlib不能单独完成解压文件的操作,所以要结合minizip的API函数来解压。


二、minizip

minizip是zlib的上层库,它封装了与zip文件相关的操作。

其中解压的API函数说明:

  (1)unzFile unzOpen(const char *path);  //打开zip文件

  (2)int unzClose(unzFile file);//关闭zip文件

  (3)int unzGetGlobalInfo(unzFile file, unz_global_info *pglobal_info);//获取zip压缩文件的信息

  (4)int unzGoToNextFile(unzFile file);//获取下一个文件

  (5)int unzGetCurrentFileInfo(unzFile file, unz_file_info *pfile_info, char *szFileName, uLong fileNameBufferSize, void *extraField, uLong extraFieldBufferSize, char *szComment, uLong commentBufferSize); //获取文件的信息

  (6)int unzOpenCurrentFile(unzFile file); //打开当前文件

  (7)int unzCloseCurrentFile(unzFile file); //关闭当前文件

  (8)int unzReadCurrentFile(unzFile file, voidp buf, unsigned len);//读当前文件

三、环境配置

在VC下要加入如下文件:

zlib.h

zlib.lib

unzip.h

unzip.cpp

上述文件均可在网上很容易找到,这里不提供链接了。


四、示例代码

 
#include <iostream>
#include <string>
#include <windows.h>
#include "unzip.h"


using namespace std;


int main()
{
TCHAR * mUnPackPath = L"Google_usb_driver";
TCHAR * mZipFileFullPath = L"Google_usb_driver.zip";

HZIP hz = OpenZip(mZipFileFullPath,0);
if (hz == 0)
{
//打开Zip文件失败
cout << "打开文件失败" << endl;
return -1;
}


ZRESULT zr = SetUnzipBaseDir(hz,mUnPackPath);
if (zr != ZR_OK)
{
//打开ZIP文件失败
cout << "打开ZIP文件失败" << endl;
CloseZip(hz);
return -1;
}


ZIPENTRY ze;
zr = GetZipItem(hz,-1,&ze);
if (zr != ZR_OK)
{
//获取Zip文件内容失败
cout << "获取文件内容失败" << endl;
CloseZip(hz);
return -1;
}


int numitems = ze.index;
for (int i = 0;i < numitems;i ++)
{
zr = GetZipItem(hz,i,&ze);
zr = UnzipItem(hz,i,ze.name);
if (zr != ZR_OK)
{
cout << "获取Zip文件内容失败" << endl;
CloseZip(hz);
return -1;
}
}


CloseZip(hz);
cout << "解压成功" << endl;
return 0;
}



0 0