下载zlib库源码:http://www.zlib.net/
编译lib库
选择对应的Visual Studio工程目录打开zlibvc.sln文件,工程设置为Release模式,选中zlibstat项,将预处理器中的ASMINF宏删除(重要否则会产生 L_get_length_code_mmx 的崩溃)
编译成功后会生成zlibstat.lib库
将 zlibstat.lib,zlib.h,zconf.h 拷贝到工程目录,并通过 属性-连接器-输入-附加依赖项 导入zlibstat.lib;
将unzip.h,unzip.c,ioapi.h,ioapi.c拷贝到工程目录,并添加到工程
这几个文件在源码中的位置如图
测试工程的设置:
核心代码:
#include <iostream>
#include <string>
#include "unzip.h"
#include <direct.h>bool unzipCurrentFile(unzFile uf, const char *destFolder)
{char szFilePath[512];unz_file_info64 FileInfo;if (unzGetCurrentFileInfo64(uf, &FileInfo, szFilePath, sizeof(szFilePath), NULL, 0, NULL, 0) != UNZ_OK)return false;size_t len = strlen(szFilePath);if (len <= 0){return false;}std::string fullFileName = destFolder;fullFileName = fullFileName + "\\" + szFilePath;if (szFilePath[len - 1] == '\\' || szFilePath[len - 1] == '/'){_mkdir(fullFileName.c_str());return true;}auto file = fopen(fullFileName.c_str(), "wb");if (file == nullptr){return false;}const int BUFFER_SIZE = 4096;unsigned char byBuffer[BUFFER_SIZE];if (unzOpenCurrentFile(uf) != UNZ_OK){fclose(file);return false;}while (true){int nSize = unzReadCurrentFile(uf, byBuffer, BUFFER_SIZE);if (nSize < 0){unzCloseCurrentFile(uf);fclose(file);return false;}else if (nSize == 0){break;}else{size_t wSize = fwrite(byBuffer, 1, nSize, file);if (wSize != nSize){unzCloseCurrentFile(uf);fclose(file);return false;}}}unzCloseCurrentFile(uf);fclose(file);return true;
}bool unzipFile(std::string zipFileName, std::string goalPath)
{unzFile uf = unzOpen64(zipFileName.c_str());if (uf == NULL)return false;unz_global_info64 gi;if (unzGetGlobalInfo64(uf, &gi) != UNZ_OK){unzClose(uf);return false;}std::string path=zipFileName;auto pos = path.find_last_of("/\\");if (pos != std::string::npos)path.erase(path.begin() + pos, path.end());for (int i = 0; i < gi.number_entry; ++i){if (!unzipCurrentFile(uf, goalPath.c_str())){unzClose(uf);return false;}if (i < gi.number_entry - 1){if (unzGoToNextFile(uf) != UNZ_OK){unzClose(uf);return false;}}}unzClose(uf);return true;
}int main()
{unzipFile("test.zip", "C:\\Users\\Administrator\\Desktop\\cc");getchar();return 0;
}
博友反馈解压的目标目录需要存在
即 C:\\Users\\Administrator\\Desktop\\cc文件夹需要提前创建