压缩解压缩的函数库zlib的使用

本文介绍了zlib压缩库的基本用法,包括压缩和解压缩文件的过程,并通过一个简单的示例展示了如何使用compress和uncompress函数进行数据的压缩与还原。

zlib是一套公开源代码的压缩,解压缩的函数库,提供了很多文件操作的方法,但是他不是一套类库,所以有兴趣的人都可以把他进行封装,实现自己的类库,和更高层的接口。
具体的介绍可以参考http://www.gzip.org/zlib/主页,这里有详细介绍。

    这里简单实现了zlib的最简单的用法,压缩一个文件,通过使用文件映射来实现的。
    包含头文件 zlib.h 和 zconf.h 和 zdll.lib

HANDLE hFile, hFileToWrite;

//打开要进行压缩的文件
hFile = CreateFile(strFilePath, // file name
    GENERIC_READ, // open for reading
    FILE_SHARE_READ, // share for reading
    NULL, // no security
    OPEN_EXISTING, // existing file only
    FILE_ATTRIBUTE_NORMAL, // normal file
    NULL); // no attr. template

if (hFile == INVALID_HANDLE_VALUE)
{
    AfxMessageBox("Could not open file to read"); // process error
    return;
}

HANDLE hMapFile, hMapFileToWrite;

//创建一个文件映射
hMapFile = CreateFileMapping(hFile, // Current file handle.
NULL, // Default security.
PAGE_READONLY, // Read/write permission.
0, // Max. object size.
0, // Size of hFile.
"ZipTestMappingObjectForRead"); // Name of mapping object.

if (hMapFile == NULL)
{
AfxMessageBox("Could not create file mapping object");
return;
}

LPVOID lpMapAddress, lpMapAddressToWrite;

//创建一个文件映射的视图用来作为source
lpMapAddress = MapViewOfFile(hMapFile, // Handle to mapping object.
FILE_MAP_READ, // Read/write permission
0, // Max. object size.
0, // Size of hFile.
0); // Map entire file.

if (lpMapAddress == NULL)
{
AfxMessageBox("Could not map view of file");
return;
}

//////////////////////////////////////////////////////////////////////////////////
DWORD dwFileLength,dwFileLengthToWrite;
dwFileLength = GetFileSize(hFile, NULL);
//因为压缩函数的输出缓冲必须比输入大0.1% + 12 然后一个DWORD用来保存压缩前的大小,
// 解压缩的时候用,当然还可以保存更多的信息,这里用不到
dwFileLengthToWrite = (double)dwFileLength*1.001 + 12 + sizeof(DWORD);

//以下是创建一个文件,用来保存压缩后的文件
hFileToWrite = CreateFile("demoFile.gz", // create demo.gz
GENERIC_WRITE|GENERIC_READ, // open for writing
0, // do not share
NULL, // no security
CREATE_ALWAYS, // overwrite existing
FILE_ATTRIBUTE_NORMAL , // normal file
NULL); // no attr. template

if (hFileToWrite == INVALID_HANDLE_VALUE)
{
AfxMessageBox("Could not open file to write"); // process error
return;
}

hMapFileToWrite = CreateFileMapping(hFileToWrite, // Current file handle.
NULL, // Default security.
PAGE_READWRITE, // Read/write permission.
0, // Max. object size.
dwFileLengthToWrite, // Size of hFile.
"ZipTestMappingObjectForWrite"); // Name of mapping object.

if (hMapFileToWrite == NULL)
{
AfxMessageBox("Could not create file mapping object for write");
return;
}

lpMapAddressToWrite = MapViewOfFile(hMapFileToWrite, // Handle to mapping object.
FILE_MAP_WRITE, // Read/write permission
0, // Max. object size.
0, // Size of hFile.
0); // Map entire file.

if (lpMapAddressToWrite == NULL)
{
AfxMessageBox("Could not map view of file");
return;
}

//这里是将压缩前的大小保存在文件的第一个DWORD里面
LPVOID pBuf = lpMapAddressToWrite;
(*(DWORD*)pBuf) = dwFileLength;
pBuf = (DWORD*)pBuf + 1;


//////////////////////////////////////////////////////////////////////

//这里就是最重要的,zlib里面提供的一个方法,将源缓存的数据压缩至目的缓存
//原形如下:
//int compress (Bytef *dest, uLongf *destLen, const Bytef *source, uLong sourceLen);
//参数destLen返回实际压缩后的文件大小。
compress((Bytef*)pBuf,&dwFileLengthToWrite, (Bytef*)lpMapAddress, dwFileLength);

//////////////////////////////////////////////////////////////////////

UnmapViewOfFile(lpMapAddress);
CloseHandle(hMapFile);
CloseHandle(hFile);

UnmapViewOfFile(lpMapAddressToWrite);
CloseHandle(hMapFileToWrite);
//这里将文件大小重新设置一下
SetFilePointer(hFileToWrite,dwFileLengthToWrite + sizeof(DWORD) ,NULL,FILE_BEGIN);
SetEndOfFile(hFileToWrite);
CloseHandle(hFileToWrite);

解压缩的方法其他地方都一样,不同的就是使用方法是uncompress而不是compress
原形如下:
int uncompress (Bytef *dest, uLongf *destLen, const Bytef *source, uLong sourceLen);

 

------------------------------------------------------------------------------------------------------------------------------

zlib 是通用的压缩库,提供了一套 in-memory 压缩和解压函数,并能检测解压出来的数据的完整性(integrity)zlib 也支持读写 gzip (.gz) 格式的文件。下面介绍两个最有用的函数——compress  uncompress

 

int compress(Bytef *dest, uLongf *destLen, const Bytef *source, uLong sourceLen);

compress函数将 source 缓冲区中的内容压缩到 dest 缓冲区。 sourceLen 表示source 缓冲区的大小(以字节计)。注意函数的第二个参数 destLen 是传址调用。当调用函数时,destLen表示 dest 缓冲区的大小,destLen > (sourceLen + 12)*100.1%。当函数退出后,destLen 表示压缩后缓冲区的实际大小。此时 destLen /sourceLen 正好是压缩率。

compress 若成功,则返回 Z_OK;若没有足够内存,则返回 Z_MEM_ERROR;若输出缓冲区不够大,则返回 Z_BUF_ERROR

 

int uncompress(Bytef *dest, uLongf *destLen, const Bytef *source, uLong sourceLen);

uncompress 函数将 source 缓冲区的内容解压缩到 dest 缓冲区。sourceLen source 缓冲区的大小(以字节计)。注意函数的第二个参数 destLen 是传址调用。当调用函数时,destLen 表示 dest 缓冲区的大小, dest 缓冲区要足以容下解压后的数据。在进行解压缩时,需要提前知道被压缩的数据解压出来会有多大。这就要求在进行压缩之前,保存原始数据的大小(也就是解压后的数据的大小)。这不是 zlib 函数库的功能,需要我们做额外的工作。当函数退出后, destLen 是解压出来的数据的实际大小。

uncompress 若成功,则返回 Z_OK ;若没有足够内存,则返回 Z_MEM_ERROR;若输出缓冲区不够大,则返回 Z_BUF_ERROR。若输入数据有误,则返回 Z_DATA_ERROR

zlib 带的 example.c 是个很好的学习范例,值得一观。我们写个程序,验证 zlib 的压缩功能。所写的测试程序保存为 testzlib.cpp ,放在 zlib-1.1.4 目录下。程序源代码:

// testzlib.cpp  简单测试 zlib 的压缩功能

#include <cstring>

#include <cstdlib>

#include <iostream>

#include "zlib.h"

 

using namespace std;

 

int main()

{

    int err;

    Byte compr[200], uncompr[200];    // big enough

    uLong comprLen, uncomprLen;

    const char* hello = "12345678901234567890123456789012345678901234567890";

 

    uLong len = strlen(hello) + 1;

    comprLen  = sizeof(compr) / sizeof(compr[0]);

 

    err = compress(compr, &comprLen, (const Bytef*)hello, len);

 

    if (err != Z_OK) {

        cerr << "compess error: " << err << '/n';

        exit(1);

    }

    cout << "orignal size: " << len

         << " , compressed size : " << comprLen << '/n';

 

    strcpy((char*)uncompr, "garbage");

 

    err = uncompress(uncompr, &uncomprLen, compr, comprLen);

 

    if (err != Z_OK) {

        cerr << "uncompess error: " << err << '/n';

        exit(1);

    }

    cout << "orignal size: " << len

         << " , uncompressed size : " << uncomprLen << '/n';

 

    if (strcmp((char*)uncompr, hello)) {

        cerr << "BAD uncompress!!!/n";

        exit(1);

    } else {

        cout << "uncompress() succeed: /n" << (char *)uncompr;

    }

}

编译执行这个程序,输出应该是

D:/libpng/zlib-1.1.4>bcc32 testzlib.cpp zlib.lib

 

D:/libpng/zlib-1.1.4>testzlib

orignal size: 51 , compressed size : 22

orignal size: 51 , uncompressed size : 51

uncompress() succeed:

12345678901234567890123456789012345678901234567890

评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值