百度360必应搜狗淘宝本站头条
当前位置:网站首页 > IT技术 > 正文

使用Zlib库进行多文件或者多文件夹的压缩解压缩

wptr33 2025-02-26 14:06 15 浏览

zlib库可在git上自己clone下来然后使用cmake工具生成解决方案,编译、生成zlib二进制文件。然后将zlib库引入项目:

//zlib库支持
#include "../zlib/include/zlib.h"
#ifdef _DEBUG
#pragma comment(lib, "../zlib/lib/zlibd.lib")
#else
#pragma comment(lib, "../zlib/lib/zlib.lib")
#endif

首先我们定义一个文件结构:

typedef struct tagZipperFileInfo
{
	char m_szLocalPath[MAX_PATH];
	char m_szRootPath[MAX_PATH];
	char m_szFileName[MAX_PATH];
	size_t m_FileSize;
}ZipperFileInfo;

然后我们来处理文件的压缩,包括遍历所选的目录下的所有文件。

void OperateFolder(std::string& strFolder, std::string& strRoot, std::vector& vecZipperFiles)
{
	std::string searchPath = strFolder + "\\*";
	WIN32_FIND_DATAA findData;
	HANDLE hFind = FindFirstFileA(searchPath.c_str(), &findData);
	if (hFind == INVALID_HANDLE_VALUE) {
		//error
		return;
	}
	do {
		if (findData.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) {
			if (strcmp(findData.cFileName, ".") != 0 && strcmp(findData.cFileName, "..") != 0) 
			{
				std::string subFolderPath = strFolder + "\\" + findData.cFileName;
				OperateFolder(subFolderPath, strRoot, vecZipperFiles);
			}
		}
		else {
			std::string strLocalPath = strFolder + "\\" + findData.cFileName;
			std::string strFileRootPath = strFolder;
			std::string strFileName = findData.cFileName;

			//需要根据strRoot分割出来需要压缩文件的相对路径名
			std::string strTempPath;
			size_t start = strFileRootPath.find(strRoot);
			if (start == std::string::npos)
				strTempPath = strFileRootPath; // 如果找不到根路径,则返回完整路径
			else
			{
				if (strFileRootPath == strRoot)
					strTempPath = strFileRootPath.substr(start + strRoot.length());
				else
					strTempPath = strFileRootPath.substr(start + strRoot.length() + 1);
			}

			ZipperFileInfo zipperFile;
			memcpy(zipperFile.m_szRootPath, strTempPath.c_str(), MAX_PATH);
			memcpy(zipperFile.m_szLocalPath, strLocalPath.c_str(), MAX_PATH);
			memcpy(zipperFile.m_szFileName, strFileName.c_str(), MAX_PATH);

			//计算文件大小
			std::ifstream in(strLocalPath, std::ios::binary | std::ios::ate);
			size_t fileSize = in.tellg();
			in.seekg(0);
			in.close();
			zipperFile.m_FileSize = fileSize;

			vecZipperFiles.push_back(zipperFile);
		}
	} while (FindNextFileA(hFind, &findData) != 0);
	FindClose(hFind);
}

/*
*	strFolder	需要被压缩的文件夹
*	strOut		保存的文件
*/
void CompressFolder(std::string& strFolder, std::string& strOut)
{
	//创建压缩的目标文件
	std::ofstream dest(strOut, std::ios::binary | std::ios::trunc);
	if (!dest.is_open()) {
		//error
		return;
	}
	dest.close();

	std::vector vecZipperFiles;
	//遍历文件夹下的所有文件
	OperateFolder(strFolder, strFolder, vecZipperFiles);

	//压缩文件
	gzFile gzOut = gzopen(strOut.c_str(), "wb");
	CompressFiles(vecZipperFiles, gzOut);
	gzclose(gzOut);
}

然后进行文件压缩:

void CompressFiles(std::vector& vecZipperFiles, gzFile& gzOut)
{
	int nFileCount = vecZipperFiles.size();
	gzwrite(gzOut, reinterpret_cast(&nFileCount), 4);
	gzwrite(gzOut, reinterpret_cast(vecZipperFiles.data()), vecZipperFiles.size() * sizeof(ZipperFileInfo));

	//再往压缩文件中写入需要压缩为文件内容
	for (int i = 0; i < vecZipperFiles.size(); i++)
	{
		std::string strLocalPath = vecZipperFiles[i].m_szLocalPath;
		std::ifstream infile(strLocalPath, std::ios::binary);
		char buffer[4096];
		while (infile)
		{
			infile.read(buffer, sizeof(buffer));
			auto bytes = infile.gcount();
			if (bytes > 0)
			{
				//写入目标压缩文件
				gzwrite(gzOut, buffer, bytes);
			}
		}
		infile.close();
	}
}

以上即为文件压缩。下边我们看看对压缩的文件进行解压处理:

/*递归生成压缩文件中的目录结构:
*	strRoot	解压缩的目标目录
*	strDir	压缩文件的相对路径
*/
void CreateFolder(std::string& strRoot, std::string& strDir)
{
	size_t szPos = strDir.find_first_of("\\");
	if (szPos != std::string::npos)
	{
		std::string strName = strDir.substr(0, szPos);
		std::string strPath = strRoot + "\\" + strName;
		CreateDirectoryA(strPath.c_str(), NULL);

		std::string strSubName = strDir.substr(szPos + 1);
		std::string strTempRoot = strRoot + "\\" + strName;
		CreateFolder(strTempRoot, strSubName);
	}
	else
	{
		std::string strPath = strRoot + "\\" + strDir;
		CreateDirectoryA(strPath.c_str(), NULL);
	}
}

//strFilePath 压缩文件路径
void DecompressFiles(std::string& strFilePath)
{
	gzFile gzin = gzopen(strFilePath.c_str(), "rb");
	if (!gzin) return; //open error

	int nFileCount = 0;
	gzread(gzin, &nFileCount, 4); //读取压缩的文件数量

	// 读取文件列表信息
	std::vector vecZipperFiles;
	ZipperFileInfo zipperFile;
	for (int i = 0; i < nFileCount; i++)
	{
		if (gzread(gzin, &zipperFile, sizeof(ZipperFileInfo)) == sizeof(ZipperFileInfo))
			vecZipperFiles.push_back(zipperFile);
	}

	SStringW sstrAppPath = CGlobalUnits::GetInstance()->m_sstrAppPath;
	std::string strAppPath = S_CW2A(sstrAppPath);

	//先创建个输出目录
	size_t szPos = strFilePath.find_last_of("\\");
	if (szPos != std::string::npos)
	{
		std::string strTmp = strFilePath.substr(szPos + 1);
		//分解出name
		size_t szName = strTmp.find_last_of(".");
		if (szName != std::string::npos)
		{
			std::string strName = strTmp.substr(0, szName);
			strAppPath += strName;
		}
	}
	CreateDirectoryA(strAppPath.c_str(), NULL);

	//解压文件
	for (int i = 0; i < vecZipperFiles.size(); i++)
	{
		ZipperFileInfo& info = vecZipperFiles[i];
		std::string strRoot = info.m_szRootPath;

		std::string strPath;
		if (strRoot == "")  //根目录下
			strPath = strAppPath + "\\" + info.m_szFileName;
		else
		{
			CreateFolder(strAppPath, strRoot);
			strPath = strAppPath + "\\" + strRoot + "\\" + info.m_szFileName;
		}
		std::ofstream outFile(strPath, std::ios::binary);
		if (!outFile) continue;  //error 
		char buffer[4096];
		size_t fileSize = info.m_FileSize;
		while (fileSize > 0)
		{
			size_t bytesToRead = std::min(static_cast(4096), fileSize);
			int bytesRead = gzread(gzin, buffer, bytesToRead);
			if (bytesRead <= 0) break; //read error
			outFile.write(buffer, bytesRead);
			fileSize -= bytesRead;
		}
		outFile.close();
	}

	gzclose(gzin);
}

以上即为使用zlib库进行文件的压缩解压缩相关的代码。但是以上处理非标准的压缩解压缩,压缩的文件不能被市面通用的zip软件解压也不能解压市面通用软件压缩的zip包。

相关推荐

redis的八种使用场景

前言:redis是我们工作开发中,经常要打交道的,下面对redis的使用场景做总结介绍也是对redis举报的功能做梳理。缓存Redis最常见的用途是作为缓存,用于加速应用程序的响应速度。...

基于Redis的3种分布式ID生成策略

在分布式系统设计中,全局唯一ID是一个基础而关键的组件。随着业务规模扩大和系统架构向微服务演进,传统的单机自增ID已无法满足需求。高并发、高可用的分布式ID生成方案成为构建可靠分布式系统的必要条件。R...

基于OpenWrt系统路由器的模式切换与网页设计

摘要:目前商用WiFi路由器已应用到多个领域,商家通过给用户提供一个稳定免费WiFi热点达到吸引客户、提升服务的目标。传统路由器自带的Luci界面提供了工厂模式的Web界面,用户可通过该界面配置路...

这篇文章教你看明白 nginx-ingress 控制器

主机nginx一般nginx做主机反向代理(网关)有以下配置...

如何用redis实现注册中心

一句话总结使用Redis实现注册中心:服务注册...

爱可可老师24小时热门分享(2020.5.10)

No1.看自己以前写的代码是种什么体验?No2.DooM-chip!国外网友SylvainLefebvre自制的无CPU、无操作码、无指令计数器...No3.我认为CS学位可以更好,如...

Apportable:拯救程序员,IOS一秒变安卓

摘要:还在为了跨平台使用cocos2d-x吗,拯救objc程序员的奇葩来了,ApportableSDK:FreeAndroidsupportforcocos2d-iPhone。App...

JAVA实现超买超卖方案汇总,那个最适合你,一篇文章彻底讲透

以下是几种Java实现超买超卖问题的核心解决方案及代码示例,针对高并发场景下的库存扣减问题:方案一:Redis原子操作+Lua脚本(推荐)//使用Redis+Lua保证原子性publicbo...

3月26日更新 快速施法自动施法可独立设置

2016年3月26日DOTA2有一个79.6MB的更新主要是针对自动施法和快速施法的调整本来内容不多不少朋友都有自动施法和快速施法的困扰英文更新日志一些视觉BUG修复就不翻译了主要翻译自动施...

Redis 是如何提供服务的

在刚刚接触Redis的时候,最想要知道的是一个’setnameJhon’命令到达Redis服务器的时候,它是如何返回’OK’的?里面命令处理的流程如何,具体细节怎么样?你一定有问过自己...

lua _G、_VERSION使用

到这里我们已经把lua基础库中的函数介绍完了,除了函数外基础库中还有两个常量,一个是_G,另一个是_VERSION。_G是基础库本身,指向自己,这个变量很有意思,可以无限引用自己,最后得到的还是自己,...

China&#39;s top diplomat to chair third China-Pacific Island countries foreign ministers&#39; meeting

BEIJING,May21(Xinhua)--ChineseForeignMinisterWangYi,alsoamemberofthePoliticalBureau...

移动工作交流工具Lua推出Insights数据分析产品

Lua是一个适用于各种职业人士的移动交流平台,它在今天推出了一项叫做Insights的全新功能。Insights是一个数据平台,客户可以在上面实时看到员工之间的交流情况,并分析这些情况对公司发展的影响...

Redis 7新武器:用Redis Stack实现向量搜索的极限压测

当传统关系型数据库还在为向量相似度搜索的性能挣扎时,Redis7的RedisStack...

Nginx/OpenResty详解,Nginx Lua编程,重定向与内部子请求

重定向与内部子请求Nginx的rewrite指令不仅可以在Nginx内部的server、location之间进行跳转,还可以进行外部链接的重定向。通过ngx_lua模块的Lua函数除了能实现Nginx...