在C++中,壓縮文件夾通常需要使用第三方庫,例如 zlib、minizip 或者 libarchive。以下是一個使用 minizip 庫的示例,演示如何壓縮文件夾及其內容:
首先,確保已經安裝了 minizip 庫。在 Ubuntu 系統上,可以使用以下命令安裝:
sudo apt-get install libminizip-dev
接下來,編寫一個 C++ 程序來壓縮文件夾:
#include<iostream>
#include<string>
#include<vector>
#include <dirent.h>
#include <sys/stat.h>
#include "mz_compat.h"
bool is_directory(const std::string &path) {
struct stat st;
if (stat(path.c_str(), &st) == 0 && S_ISDIR(st.st_mode)) {
return true;
}
return false;
}
std::vector<std::string> list_files(const std::string &folder) {
std::vector<std::string> files;
DIR *dir = opendir(folder.c_str());
if (dir != nullptr) {
dirent *entry;
while ((entry = readdir(dir)) != nullptr) {
if (entry->d_name[0] != '.') {
std::string path = folder + "/" + entry->d_name;
if (is_directory(path)) {
auto sub_files = list_files(path);
files.insert(files.end(), sub_files.begin(), sub_files.end());
} else {
files.push_back(path);
}
}
}
closedir(dir);
}
return files;
}
int compress_folder(const std::string &input_folder, const std::string &output_file) {
zipFile zf = zipOpen64(output_file.c_str(), APPEND_STATUS_CREATE);
if (zf == nullptr) {
std::cerr << "Failed to create zip file: "<< output_file<< std::endl;
return -1;
}
auto files = list_files(input_folder);
for (const auto &file : files) {
zip_fileinfo file_info = {};
int err = zipOpenNewFileInZip4_64(zf, file.substr(input_folder.length() + 1).c_str(), &file_info,
nullptr, 0, nullptr, 0, nullptr, Z_DEFLATED, Z_DEFAULT_COMPRESSION, 0,
-MAX_WBITS, DEF_MEM_LEVEL, Z_DEFAULT_STRATEGY, nullptr, 0, 0, 0);
if (err != ZIP_OK) {
std::cerr << "Failed to open file in zip: "<< file<< std::endl;
zipClose(zf, nullptr);
return -1;
}
FILE *f = fopen(file.c_str(), "rb");
if (f == nullptr) {
std::cerr << "Failed to open file: "<< file<< std::endl;
zipCloseFileInZip(zf);
zipClose(zf, nullptr);
return -1;
}
char buffer[4096];
size_t read_size;
while ((read_size = fread(buffer, 1, sizeof(buffer), f)) > 0) {
err = zipWriteInFileInZip(zf, buffer, static_cast<unsigned int>(read_size));
if (err < 0) {
std::cerr << "Failed to write file to zip: "<< file<< std::endl;
fclose(f);
zipCloseFileInZip(zf);
zipClose(zf, nullptr);
return -1;
}
}
fclose(f);
zipCloseFileInZip(zf);
}
zipClose(zf, nullptr);
return 0;
}
int main() {
std::string input_folder = "/path/to/input/folder";
std::string output_file = "/path/to/output/file.zip";
int result = compress_folder(input_folder, output_file);
if (result == 0) {
std::cout << "Folder successfully compressed!"<< std::endl;
} else {
std::cerr << "Failed to compress folder."<< std::endl;
}
return result;
}
這個程序首先遞歸地列出文件夾中的所有文件,然后使用 minizip 庫將這些文件添加到壓縮文件中。請注意,您需要根據實際情況修改 input_folder
和 output_file
變量的值。