unzip.cpp源码
时间: 2023-10-30 16:06:03 浏览: 43
以下是一个简单的unzip.cpp源码示例,用于解压缩zip文件:
```c++
#include "unzip.h"
#include "zip.h"
// 定义一个回调函数,用于更新解压进度
int OnExtractUpdate(void* pUnzip, long long bytesWritten, long long totalBytes)
{
int nPercent = (int)(bytesWritten * 100 / totalBytes);
printf("Extract Progress: %d%%\n", nPercent);
return 1; // 返回1表示继续解压缩,返回0表示取消解压缩
}
// 解压缩zip文件
int UnzipFile(const char* szZipFile, const char* szDestFolder)
{
// 打开zip文件
unzFile zipFile = unzOpen(szZipFile);
if (!zipFile)
{
printf("Failed to open zip file: %s\n", szZipFile);
return -1;
}
// 获取zip文件信息
unz_global_info globalInfo;
if (unzGetGlobalInfo(zipFile, &globalInfo) != UNZ_OK)
{
printf("Failed to get zip file info: %s\n", szZipFile);
unzClose(zipFile);
return -1;
}
// 解压缩每个文件
char szDestFilePath[256];
for (uLong i = 0; i < globalInfo.number_entry; i++)
{
// 获取文件信息
unz_file_info fileInfo;
char szFileName[256];
if (unzGetCurrentFileInfo(zipFile, &fileInfo, szFileName, sizeof(szFileName), NULL, 0, NULL, 0) != UNZ_OK)
{
printf("Failed to get file info: %s\n", szFileName);
unzClose(zipFile);
return -1;
}
// 构造解压缩后的文件路径
sprintf_s(szDestFilePath, "%s/%s", szDestFolder, szFileName);
// 如果是目录,则创建目录
if (szFileName[strlen(szFileName) - 1] == '/')
{
CreateDirectory(szDestFilePath, NULL);
continue;
}
// 创建目录
char szDestFolderCopy[256];
strcpy_s(szDestFolderCopy, szDestFilePath);
char* pLastSlash = strrchr(szDestFolderCopy, '/');
if (pLastSlash)
{
*pLastSlash = '\0';
CreateDirectory(szDestFolderCopy, NULL);
}
// 打开文件
if (unzOpenCurrentFile(zipFile) != UNZ_OK)
{
printf("Failed to open file: %s\n", szFileName);
unzClose(zipFile);
return -1;
}
// 创建目标文件
FILE* destFile = fopen(szDestFilePath, "wb");
if (!destFile)
{
printf("Failed to create file: %s\n", szDestFilePath);
unzCloseCurrentFile(zipFile);
unzClose(zipFile);
return -1;
}
// 读取并写入文件
char szBuffer[1024];
int nReadBytes = 0;
do
{
nReadBytes = unzReadCurrentFile(zipFile, szBuffer, sizeof(szBuffer));
if (nReadBytes > 0)
{
fwrite(szBuffer, 1, nReadBytes, destFile);
}
} while (nReadBytes > 0);
// 关闭文件
fclose(destFile);
// 更新解压进度
OnExtractUpdate(NULL, i + 1, globalInfo.number_entry);
// 关闭当前文件
unzCloseCurrentFile(zipFile);
}
// 关闭zip文件
unzClose(zipFile);
printf("Extract Finished!\n");
return 0;
}
```
上述代码使用了zlib库中的unzip.h和zip.h头文件,需要在项目中添加zlib的库文件和头文件。该代码实现了解压缩zip文件的基本功能,并且提供了一个回调函数用于更新解压进度。你可以根据自己的需要对代码进行修改和扩展。