在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
变量的值。