在C++中使用zlib库进行文件的压缩和解压缩操作可以按照以下步骤进行:
#include <zlib.h>
FILE *sourceFile = fopen("source.txt", "rb");
FILE *destFile = fopen("compressed.gz", "wb");
#define CHUNK 16384
char in[CHUNK];
char out[CHUNK];
z_stream strm;
strm.zalloc = Z_NULL;
strm.zfree = Z_NULL;
strm.opaque = Z_NULL;
deflateInit
函数初始化压缩上下文,并调用deflate
函数进行压缩:if (deflateInit(&strm, Z_BEST_COMPRESSION) != Z_OK) {
// 处理初始化失败的情况
}
while (!feof(sourceFile)) {
strm.avail_in = fread(in, 1, CHUNK, sourceFile);
strm.next_in = (Bytef *)in;
do {
strm.avail_out = CHUNK;
strm.next_out = (Bytef *)out;
deflate(&strm, Z_FINISH);
fwrite(out, 1, CHUNK - strm.avail_out, destFile);
} while (strm.avail_out == 0);
}
deflateEnd(&strm);
inflateInit
函数初始化解压上下文,并调用inflate
函数进行解压:if (inflateInit(&strm) != Z_OK) {
// 处理初始化失败的情况
}
while (!feof(sourceFile)) {
strm.avail_in = fread(in, 1, CHUNK, sourceFile);
strm.next_in = (Bytef *)in;
do {
strm.avail_out = CHUNK;
strm.next_out = (Bytef *)out;
inflate(&strm, Z_NO_FLUSH);
fwrite(out, 1, CHUNK - strm.avail_out, destFile);
} while (strm.avail_out == 0);
}
inflateEnd(&strm);
fclose(sourceFile);
fclose(destFile);
通过以上步骤,就可以使用zlib库实现文件的压缩和解压缩操作。需要注意的是,在实际应用中,还需要处理错误和异常情况,以及添加适当的错误处理和日志记录。