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

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

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

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包。

相关推荐

oracle数据导入导出_oracle数据导入导出工具

关于oracle的数据导入导出,这个功能的使用场景,一般是换服务环境,把原先的oracle数据导入到另外一台oracle数据库,或者导出备份使用。只不过oracle的导入导出命令不好记忆,稍稍有点复杂...

继续学习Python中的while true/break语句

上次讲到if语句的用法,大家在微信公众号问了小编很多问题,那么小编在这几种解决一下,1.else和elif是子模块,不能单独使用2.一个if语句中可以包括很多个elif语句,但结尾只能有一个else解...

python continue和break的区别_python中break语句和continue语句的区别

python中循环语句经常会使用continue和break,那么这2者的区别是?continue是跳出本次循环,进行下一次循环;break是跳出整个循环;例如:...

简单学Python——关键字6——break和continue

Python退出循环,有break语句和continue语句两种实现方式。break语句和continue语句的区别:break语句作用是终止循环。continue语句作用是跳出本轮循环,继续下一次循...

2-1,0基础学Python之 break退出循环、 continue继续循环 多重循

用for循环或者while循环时,如果要在循环体内直接退出循环,可以使用break语句。比如计算1至100的整数和,我们用while来实现:sum=0x=1whileTrue...

Python 中 break 和 continue 傻傻分不清

大家好啊,我是大田。今天分享一下break和continue在代码中的执行效果是什么,进一步区分出二者的区别。一、continue例1:当小明3岁时不打印年龄,其余年龄正常循环打印。可以看...

python中的流程控制语句:continue、break 和 return使用方法

Python中,continue、break和return是控制流程的关键语句,用于在循环或函数中提前退出或跳过某些操作。它们的用途和区别如下:1.continue(跳过当前循环的剩余部分,进...

L017:continue和break - 教程文案

continue和break在Python中,continue和break是用于控制循环(如for和while)执行流程的关键字,它们的作用如下:1.continue:跳过当前迭代,...

作为前端开发者,你都经历过怎样的面试?

已经裸辞1个月了,最近开始投简历找工作,遇到各种各样的面试,今天分享一下。其实在职的时候也做过面试官,面试官时,感觉自己问的问题很难区分候选人的能力,最好的办法就是看看候选人的github上的代码仓库...

面试被问 const 是否不可变?这样回答才显功底

作为前端开发者,我在学习ES6特性时,总被const的"善变"搞得一头雾水——为什么用const声明的数组还能push元素?为什么基本类型赋值就会报错?直到翻遍MDN文档、对着内存图反...

2023金九银十必看前端面试题!2w字精品!

导文2023金九银十必看前端面试题!金九银十黄金期来了想要跳槽的小伙伴快来看啊CSS1.请解释CSS的盒模型是什么,并描述其组成部分。答案:CSS的盒模型是用于布局和定位元素的概念。它由内容区域...

前端面试总结_前端面试题整理

记得当时大二的时候,看到实验室的学长学姐忙于各种春招,有些收获了大厂offer,有些还在苦苦面试,其实那时候的心里还蛮忐忑的,不知道自己大三的时候会是什么样的一个水平,所以从19年的寒假放完,大二下学...

由浅入深,66条JavaScript面试知识点(七)

作者:JakeZhang转发链接:https://juejin.im/post/5ef8377f6fb9a07e693a6061目录由浅入深,66条JavaScript面试知识点(一)由浅入深,66...

2024前端面试真题之—VUE篇_前端面试题vue2020及答案

添加图片注释,不超过140字(可选)1.vue的生命周期有哪些及每个生命周期做了什么?beforeCreate是newVue()之后触发的第一个钩子,在当前阶段data、methods、com...

今年最常见的前端面试题,你会做几道?

在面试或招聘前端开发人员时,期望、现实和需求之间总是存在着巨大差距。面试其实是一个交流想法的地方,挑战人们的思考方式,并客观地分析给定的问题。可以通过面试了解人们如何做出决策,了解一个人对技术和解决问...