1.背景
上篇文章《Linux下使用zlib实现数据压缩解压》对文本数据进行压缩处理,本文再进行zlib的案例进行学习,这次整理出了文件压缩例子。
2.思路
查看 zlib-1.2.11/examples/zpipe.c代码,发现他的处理是从stdin获取原始数据,再从stdout输出处理后的数据。那么我们可以将他改成从读取指定文件内容,压缩、解压处理输出到指定文件中去。
3.实现
3.1 函数入口
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <zlib.h>
#include <assert.h>
#define SIZE_CHUNK (8 * 1024)
int main(int argc, char *argv[])
{
int res = -1;
if (argv[1] && argv[2] && argv[3] && 0 == strcmp(argv[1], "-d")) {
/* -d模式 表示压缩文件 */
res = file_deflate(argv[2], argv[3]);
}
else if (argv[1] && argv[2]) {
/* 解压文件 */
res = file_inflate(argv[1], argv[2]);
}
else {
printf("%s [ -d ] < source > < dest >\n", argv[0]);
exit(EXIT_FAILURE);
}
printf("Result:\t\t\t\t[%s]\n", res ? "Failure" : "Success");
exit(res ? EXIT_FAILURE : EXIT_SUCCESS);