您好,登錄后才能下訂單哦!
在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進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。