在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庫實現文件的壓縮和解壓縮操作。需要注意的是,在實際應用中,還需要處理錯誤和異常情況,以及添加適當的錯誤處理和日志記錄。