C++解压zip压缩文件

版权声明:所有版权归作者她的吻让他,转载请标明出处. https://blog.csdn.net/qq_37059136/article/details/83510764

前言

最近做项目需要用到网络下载压缩文件并解压至指定文件夹,本意是使用zlib库,但是花费许久时间仍没有编译通过官网的文件,于是放弃,转而寻求其他方法,在之前的博客中有说道用system调用shell命令的方式使用winrar解压,但是这种方法有一个弊端就是要求客户端必须安装winrar,虽然winrar是每个电脑都必备的一款软件但是不排除有客户端没有安装的情况,因此本人花费半天时间找到了替代方法:使用专门的zip接口,即ziputils下载链接,测试可用

附官网链接ziputils官网

正文

首先我的下载链接中有两个文件夹,分别为解压文件跟压缩文件,本人已调通解压文件功能

将解压文件夹下的

添加至项目,我的环境是VS2005

下面上代码

//将路径转为TCHAR类型
		int iUnicode = MultiByteToWideChar(CP_ACP, 0, ZIPFileName_1.c_str(), ZIPFileName_1.length(), NULL, 0);
		WCHAR* pwUnicode = new WCHAR[iUnicode + 2];
		if (pwUnicode)
		{
			ZeroMemory(pwUnicode, iUnicode + 2);
		}

		MultiByteToWideChar(CP_ACP, 0, ZIPFileName_1.c_str(), ZIPFileName_1.length(), pwUnicode, iUnicode);

		pwUnicode[iUnicode] = '\0';
		pwUnicode[iUnicode+1] = '\0';

		//解压文件
		SetCurrentDirectoryA(strdec.c_str());//将进程的工作目录移动到该参数所指的目录下,该目录为winrar.exe的默认文件路径
		//解压文件会直接在项目的.vcproj目录下进行
		HZIP hz = OpenZip(pwUnicode,NULL);
		ZIPENTRY ze; 
		GetZipItem(hz,-1,&ze); 
		int numitems = ze.index;
		for (int zi = 0; zi < numitems; zi++)
		{
			ZIPENTRY ze; 
			GetZipItem(hz, zi, &ze);
			UnzipItem(hz, zi,ze.name);         
		}
		CloseZip(hz);

经本人半天调试并阅读官网说明,ziputils接口全部使用TCHAR类型参数,所以要将你的解压路径转换成TCHAR类型

SetCurrentDirectoryA(strdec.c_str());这句是将解压的工作目录切换至你想要的地方,可以删去,不影响功能

下面附带官网示例:

①从现有文件创建zip

// We place the file "simple.bmp" inside, but inside
// the zipfile it will actually be called "znsimple.bmp".
// Similarly the textfile.

HZIP hz = CreateZip("simple1.zip",0);
ZipAdd(hz,"znsimple.bmp",  "simple.bmp");
ZipAdd(hz,"znsimple.txt",  "simple.txt");
CloseZip(hz);

②解压压缩文件

HZIP hz = OpenZip("\\simple1.zip",0);
ZIPENTRY ze; 
GetZipItem(hz,-1,&ze);
int numitems=ze.index;
// -1 gives overall information about the zipfile
for (int zi=0; zi<numitems; zi++)
{ ZIPENTRY ze; GetZipItem(hz,zi,&ze); // fetch individual details
  UnzipItem(hz, zi, ze.name);         // e.g. the item's name.
}
CloseZip(hz);

③从资源压缩到内存

HRSRC hrsrc = FindResource(hInstance,MAKEINTRESOURCE(1),RT_RCDATA);
HANDLE hglob = LoadResource(hInstance,hrsrc);
void *zipbuf = LockResource(hglob);
unsigned int ziplen = SizeofResource(hInstance,hrsrc);
hz = OpenZip(zipbuf, ziplen, 0);
ZIPENTRY ze; int i; FindZipItem(hz,"sample.jpg",true,&i,&ze);
// that lets us search for an item by filename.
// Now we unzip it to a membuffer.
char *ibuf = new char[ze.unc_size];
UnzipItem(hz,i, ibuf, ze.unc_size);
...
delete[] ibuf;
CloseZip(hz);
// note: no need to free resources obtained through Find/Load/LockResource

④按块拆分到元容器

char buf[1024]; ZRESULT zr=ZR_MORE; unsigned long totsize=0;
while (zr==ZR_MORE)
{ zr = UnzipItem(hz,i, buf,1024);
  unsigned long bufsize=1024; if (zr==ZR_OK) bufsize=ze.unc_size-totsize;
  ... maybe write the buffer to a disk file here
  totsize+=bufsize;
}

由于本次项目没有全部写完,暂时不上传项目

猜你喜欢

转载自blog.csdn.net/qq_37059136/article/details/83510764