在C++中,我们可以使用第三方库来实现文件的解压和压缩
首先,你需要安装一个名为minizip
的库。这个库是zlib库的一个扩展,用于处理ZIP文件。你可以从这里下载它:https://github.com/madler/minizip
将minizip库添加到你的C++项目中。具体方法取决于你使用的开发环境和构建系统。例如,如果你使用的是CMake,你可以在CMakeLists.txt
文件中添加以下内容:
find_package(minizip REQUIRED)
include_directories(${MINIZIP_INCLUDE_DIRS})
target_link_libraries(your_target_name ${MINIZIP_LIBRARIES})
解压ZIP文件:
#include <iostream>
#include <fstream>
#include <vector>
#include <minizip/unzip.h>
bool UnzipFile(const std::string& zipFilePath, const std::string& destDirectory) {
unzFile uf = unzOpen(zipFilePath.c_str());
if (uf == nullptr) {
std::cerr << "Error opening zip file: " << zipFilePath << std::endl;
return false;
}
unz_global_info gi;
if (unzGetGlobalInfo(uf, &gi) != UNZ_OK) {
std::cerr << "Error getting zip file info: " << zipFilePath << std::endl;
unzClose(uf);
return false;
}
for (unsigned int i = 0; i < gi.number_of_files; ++i) {
unz_file_info fi;
if (unzGetCurrentFileInfo(uf, &fi, nullptr, 0, nullptr, 0, nullptr, 0) != UNZ_OK) {
std::cerr << "Error getting file info: " << zipFilePath << std::endl;
continue;
}
std::vector<char> buffer(fi.uncompressed_size);
if (unzReadCurrentFile(uf, buffer.data(), fi.uncompressed_size) != UNZ_OK) {
std::cerr << "Error reading file: " << zipFilePath << std::endl;
continue;
}
std::string fileName = fi.filename;
std::string destPath = destDirectory + "/" + fileName;
std::ofstream outputFile(destPath, std::ios::binary);
if (!outputFile) {
std::cerr << "Error creating output file: " << destPath << std::endl;
continue;
}
outputFile.write(buffer.data(), fi.uncompressed_size);
if (!outputFile) {
std::cerr << "Error writing to output file: " << destPath << std::endl;
}
}
unzClose(uf);
return true;
}
压缩文件:
#include <iostream>
#include <fstream>
#include <vector>
#include <minizip/zip.h>
bool ZipFile(const std::string& zipFilePath, const std::string& srcDirectory) {
zipFile zf = zipOpen(zipFilePath.c_str(), APPEND_STATUS_CREATE);
if (zf == nullptr) {
std::cerr << "Error opening zip file: " << zipFilePath << std::endl;
return false;
}
for (const auto& entry : std::filesystem::recursive_directory_iterator(srcDirectory)) {
if (entry.is_regular_file()) {
std::string relativePath = srcDirectory / entry.path();
zipOpenNewFileInZip(zf, relativePath.c_str(), nullptr, 0, nullptr, 0, Z_DEFLATED, Z_DEFAULT_COMPRESSION);
std::ifstream inputStream(entry.path(), std::ios::binary);
std::vector<char> buffer((std::istreambuf_iterator<char>(inputStream)), std::istreambuf_iterator<char>());
zipWriteInFileInZip(zf, buffer.data(), buffer.size());
zipCloseFileInZip(zf);
}
}
zipClose(zf);
return true;
}
这些示例展示了如何使用minizip库来解压和压缩ZIP文件。你可以根据需要修改这些函数以满足你的需求。
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。