c++使用zlib压缩文件夹
时间: 2023-07-27 10:07:06 浏览: 110
使用zlib库压缩文件夹需要进行以下步骤:
1. 遍历文件夹,将所有文件的路径存储在数组中。
2. 使用zlib库中的函数进行文件压缩。
下面是一个示例代码:
```c++
#include <iostream>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <zlib.h>
#include <dirent.h>
#include <sys/stat.h>
#define CHUNK 16384
void compressFile(const char *fileName, const char *zipName) {
int err;
FILE *sourceFile = fopen(fileName, "rb");
FILE *zipFile = fopen(zipName, "wb");
if (sourceFile == NULL || zipFile == NULL) {
std::cerr << "Failed to open file!" << std::endl;
exit(1);
}
z_stream stream;
stream.zalloc = Z_NULL;
stream.zfree = Z_NULL;
stream.opaque = Z_NULL;
err = deflateInit(&stream, Z_DEFAULT_COMPRESSION);
if (err != Z_OK) {
std::cerr << "Failed to initialize zlib!" << std::endl;
exit(1);
}
unsigned char in[CHUNK];
unsigned char out[CHUNK];
do {
stream.avail_in = fread(in, 1, CHUNK, sourceFile);
if (ferror(sourceFile)) {
std::cerr << "Failed to read file!" << std::endl;
deflateEnd(&stream);
exit(1);
}
stream.next_in = in;
do {
stream.avail_out = CHUNK;
stream.next_out = out;
err = deflate(&stream, Z_FINISH);
if (err == Z_STREAM_ERROR) {
std::cerr << "Failed to compress file!" << std::endl;
deflateEnd(&stream);
exit(1);
}
fwrite(out, 1, CHUNK - stream.avail_out, zipFile);
} while (stream.avail_out == 0);
} while (err != Z_STREAM_END);
deflateEnd(&stream);
fclose(sourceFile);
fclose(zipFile);
}
void compressFolder(const char *folderName, const char *zipName) {
DIR *dir;
struct dirent *ent;
struct stat st;
char path[1024];
dir = opendir(folderName);
if (dir == NULL) {
std::cerr << "Failed to open folder!" << std::endl;
exit(1);
}
while ((ent = readdir(dir)) != NULL) {
if (ent->d_name[0] == '.') {
continue;
}
snprintf(path, sizeof(path), "%s/%s", folderName, ent->d_name);
if (lstat(path, &st) < 0) {
std::cerr << "Failed to get file status!" << std::endl;
exit(1);
}
if (S_ISREG(st.st_mode)) {
compressFile(path, zipName);
} else if (S_ISDIR(st.st_mode)) {
compressFolder(path, zipName);
}
}
closedir(dir);
}
int main(int argc, char **argv) {
if (argc < 3) {
std::cerr << "Usage: " << argv[0] << " [folder] [zip file]" << std::endl;
return 1;
}
compressFolder(argv[1], argv[2]);
return 0;
}
```
这个程序将压缩指定文件夹中的所有文件,并将它们保存到一个zip文件中。你可以根据需要进行修改。
阅读全文