壓縮文件:
壓縮代碼
#include <stdio.h>
#include "zlib.h"
int xiaoc()
{
char *buf;
int len = 1000000; //文件長度
if ((buf = (char*)malloc(2*len)) == NULL)
{
printf("no enough memory!\n");
return -1;
}
FILE *fp = fopen("D://aaaa.log", "rb");
fread(buf, len, 1, fp);
fclose(fp);
/* 壓縮 */
gzFile fzip = gzopen("D://a.gz", "wb");
gzwrite(fzip, buf, len);
gzclose(fzip);
if (buf != NULL)
{
free(buf);
buf = NULL;
}
return 0;
}
參考文章:
http://www.cppblog.com/woaidongmao/archive/2009/09/07/95495.html
關鍵的函數有那麼幾個:
(1)int compress (Bytef *dest, uLongf *destLen, const Bytef *source, uLong sourceLen);
把源緩衝壓縮成目的緩衝, 就那麼簡單, 一個函數搞定
(2) int compress2 (Bytef *dest, uLongf *destLen,const Bytef *source, uLong sourceLen,int level);
功能和上一個函數一樣,都一個參數可以指定壓縮質量和壓縮數度之間的關係(0-9)不敢肯定這個參數的話不用太在意它,明白一個道理就好了: 要想得到高的壓縮比就要多花時間
(3) uLong compressBound (uLong sourceLen);
計算需要的緩衝區長度. 假設你在壓縮之前就想知道你的產度爲 sourcelen 的數據壓縮後有多大, 可調用這個函數計算一下,這個函數並不能得到精確的結果,但是它可以保證實際輸出長度肯定小於它計算出來的長度
(4) int uncompress (Bytef *dest, uLongf *destLen,const Bytef *source, uLong sourceLen);
解壓縮(看名字就知道了:)
(5) deflateInit() + deflate() + deflateEnd()
3個函數結合使用完成壓縮功能,具體用法看 example.c 的 test_deflate()函數. 其實 compress() 函數內部就是用這3個函數實現的(工程 zlib 的 compress.c 文件)
(6) inflateInit() + inflate() + inflateEnd()
和(5)類似,完成解壓縮功能.
(7) gz開頭的函數. 用來操作*.gz的文件,和文件stdio調用方式類似. 想知道怎麼用的話看example.c 的 test_gzio() 函數,很easy.
(8) 其他諸如獲得版本等函數就不說了.
總結: 其實只要有了compress() 和uncompress() 兩個函數,在大多數應用中就足夠了.