zlib压缩多个文件到一个压缩文件中
时间: 2024-04-10 15:34:40 浏览: 87
压缩多个文件
要将多个文件压缩到一个压缩文件中,你可以使用 zlib 库提供的函数和结构体来实现。下面是一个示例代码,演示了如何使用 zlib 压缩多个文件到一个压缩文件中:
```c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <zlib.h>
#define CHUNK_SIZE 1024
int compress_file(const char* filename, gzFile file_out) {
FILE* file_in = fopen(filename, "rb");
if (!file_in) {
return Z_ERRNO;
}
unsigned char in_buffer[CHUNK_SIZE];
unsigned char out_buffer[CHUNK_SIZE];
z_stream stream;
stream.zalloc = Z_NULL;
stream.zfree = Z_NULL;
stream.opaque = Z_NULL;
stream.avail_in = 0;
stream.next_in = Z_NULL;
int ret = deflateInit(&stream, Z_DEFAULT_COMPRESSION);
if (ret != Z_OK) {
fclose(file_in);
return ret;
}
do {
stream.avail_in = fread(in_buffer, 1, CHUNK_SIZE, file_in);
if (ferror(file_in)) {
deflateEnd(&stream);
fclose(file_in);
return Z_ERRNO;
}
stream.next_in = in_buffer;
do {
stream.avail_out = CHUNK_SIZE;
stream.next_out = out_buffer;
ret = deflate(&stream, feof(file_in) ? Z_FINISH : Z_NO_FLUSH);
if (ret == Z_STREAM_ERROR) {
deflateEnd(&stream);
fclose(file_in);
return ret;
}
unsigned int have = CHUNK_SIZE - stream.avail_out;
if (fwrite(out_buffer, 1, have, file_out) != have || ferror(file_out)) {
deflateEnd(&stream);
fclose(file_in);
return Z_ERRNO;
}
} while (stream.avail_out == 0);
} while (!feof(file_in));
deflateEnd(&stream);
fclose(file_in);
return Z_OK;
}
int main() {
const char* file1 = "file1.txt";
const char* file2 = "file2.txt";
const char* compressed_file = "compressed.gz";
gzFile file_out = gzopen(compressed_file, "wb");
if (!file_out) {
fprintf(stderr, "Failed to open file for writing: %s\n", compressed_file);
return 1;
}
int ret = compress_file(file1, file_out);
if (ret != Z_OK) {
fprintf(stderr, "Compression failed for file: %s\n", file1);
gzclose(file_out);
return 1;
}
ret = compress_file(file2, file_out);
if (ret != Z_OK) {
fprintf(stderr, "Compression failed for file: %s\n", file2);
gzclose(file_out);
return 1;
}
gzclose(file_out);
printf("Files compressed successfully!\n");
return 0;
}
```
在上面的示例代码中,我们定义了一个 `compress_file()` 函数,用于压缩单个文件。然后,在 `main()` 函数中,我们依次调用 `compress_file()` 函数压缩每个文件,并将压缩输出写入到一个 `.gz` 压缩文件中。
需要注意的是,以上代码只是一个简化的示例,实际使用 zlib 进行文件压缩时,你可能需要处理更多的错误检查和边界情况。你可以参考 zlib 的文档和示例代码来了解更多详细信息。
阅读全文