使用7Z开源SDK压缩解压数据(LzmaCompress、LzmaUncompress)

使用开源的7Z SDK中的比较重要的两个函数LzmaCompress、LzmaUncompress压缩和解压数据,这里仅仅是用来处理数据而非7Z文件,可用在网络通信、本地数据保存等需要节省空间的时候,关键是7Z的压缩比一般是最高的,对比ZIP、RAR算法。

首先是去官网下载SDK,解压后使用VC6及以上版本编译C文件夹下lzmaLib工程,生成了一个lzma.dll,体积很小,使用起来也很方便。下面是调用这两个函数来压缩和解压一个小的文件的代码,由于没有加入文件信息,所以不是标准7Z文件(本文主要是压缩数据而非文件)。

使用前需要先把7Z定义的一些常量复制过来,然后就是声明函数指针:
#define SZ_OK 0

#define SZ_ERROR_DATA 1
#define SZ_ERROR_MEM 2
#define SZ_ERROR_CRC 3
#define SZ_ERROR_UNSUPPORTED 4
#define SZ_ERROR_PARAM 5
#define SZ_ERROR_INPUT_EOF 6
#define SZ_ERROR_OUTPUT_EOF 7
#define SZ_ERROR_READ 8
#define SZ_ERROR_WRITE 9
#define SZ_ERROR_PROGRESS 10
#define SZ_ERROR_FAIL 11
#define SZ_ERROR_THREAD 12

#define SZ_ERROR_ARCHIVE 16
#define SZ_ERROR_NO_ARCHIVE 17
//定义压缩函数指针
typedef int (__stdcall *LzmaCompress)(unsigned char *, size_t*, const unsigned char *, size_t, unsigned char *,
									  size_t *, int, unsigned, int, int, int, int, int);
//定义解压函数指针
typedef int (__stdcall *LzmaUncompress)(unsigned char *dest, size_t  *destLen, const unsigned char *src, size_t  *srcLen,
			   const unsigned char *props, size_t propsSize);


HMODULE hModule = LoadLibrary(L"LZMA.dll");
	if ( NULL == hModule )
	{
		cout<<"没有找到LZMA.dll"<
涉及到文件读写,内存申请、释放之类的基础就不说了,希望对大家有所帮助。

你可能感兴趣的:(开源)