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

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

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

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 中ZSET数据类型命令使用及对应场景总结

1.zadd添加元素zaddkeyscoremember...

redis总结(redis常用)

RedisTemplate封装的工具类packagehk.com.easyview.common.helper;importcom.alibaba.fastjson.JSONObject;...

配置热更新系统(如何实现热更新)

整体设计概览┌────────────┐┌────────────────┐┌────────────┐│配置后台服务│--写入-->│Red...

java高级用法之:调用本地方法的利器JNA

简介JAVA是可以调用本地方法的,官方提供的调用方式叫做JNI,全称叫做javanativeinterface。要想使用JNI,我们需要在JAVA代码中定义native方法,然后通过javah命令...

SpringBoot:如何优雅地进行响应数据封装、异常处理

背景越来越多的项目开始基于前后端分离的模式进行开发,这对后端接口的报文格式便有了一定的要求。通常,我们会采用JSON格式作为前后端交换数据格式,从而减少沟通成本等。...

Java中有了基本类型为什么还要有包装类型(封装类型)

Java中基本数据类型与包装类型有:...

java面向对象三大特性:封装、继承、多态——举例说明(转载)

概念封装:封装就是将客观的事物抽象成类,类中存在属于这个类的属性和方法。...

java 面向对象编程:封装、继承、多态

Java中的封装(Encapsulation)、继承(Inheritance)和多态(Polymorphism)是面向对象编程的三大基本概念。它们有助于提高代码的可重用性、可扩展性和可维护性。...

怎样解析java中的封装(怎样解析java中的封装文件)

1.解析java中的封装1.1以生活中的例子为例,打开电视机的时候你只需要按下开关键,电视机就会打开,我们通过这个操作我们可以去间接的对电视机里面的元器件进行亮屏和显示界面操作,具体怎么实现我们并不...

python 示例代码(python代码详解)

以下是35个python代码示例,涵盖了从基础到高级的各种应用场景。这些示例旨在帮助你学习和理解python编程的各个方面。1.Hello,World!#python...

python 进阶突破——内置模块(Standard Library)

Python提供了丰富的内置模块(StandardLibrary),无需安装即可直接使用。以下是一些常用的内置模块及其主要功能:1.文件与系统操作...

Python程序员如何调试和分析Python脚本程序?附代码实现

调试和分析Python脚本程序调试技术和分析技术在Python开发中发挥着重要作用。调试器可以设置条件断点,帮助程序员分析所有代码。而分析器可以运行程序,并提供运行时的详细信息,同时也能找出程序中的性...

python中,函数和方法异同点(python方法和函数的区别)

在Python中,函数(Function)...

Python入门基础命令详解(python基础入门教程)

以下是Python基本命令的详解指南,专为初学者设计,涵盖基础语法、常用操作和实用示例:Python基本命令详解:入门必备指南1.Python简介特点:简洁易读、跨平台、丰富的库支持...