使用开源的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"<<endl; return 0; } LzmaCompress pLzmaCom = (LzmaCompress)GetProcAddress(hModule, "LzmaCompress"); byte prop[5] = {0}; size_t nPropSize = 5; if ( pLzmaCom ) { FILE* fp = fopen("c:\\1.jpg", "rb"); if ( NULL != fp ) { fseek(fp, 0, SEEK_END); size_t nSrcLen = ftell(fp); fseek(fp, 0, SEEK_SET); byte* pSrcData = (byte*)malloc(nSrcLen); fread(pSrcData, nSrcLen, 1, fp); fclose(fp); size_t nDesLen = nSrcLen; byte* pDesData = (byte*)malloc(nDesLen); int nRet = pLzmaCom(pDesData, &nDesLen, pSrcData, nSrcLen, prop, &nPropSize, \ 9, 1<<24, 3, 0, 2, 32, 2); if ( SZ_ERROR_OUTPUT_EOF == nRet ) {//申请内存不足 free(pDesData); nDesLen += nSrcLen; pDesData = (byte*)malloc(nDesLen); nRet = pLzmaCom(pDesData, &nDesLen, pSrcData, nSrcLen, prop, &nPropSize, \ 9, (1<<24), 3, 0, 2, 32, 2); } if ( SZ_OK == nRet ) {//压缩完成 fp = fopen("c:\\des_7z.dat", "wb+"); if ( NULL != fp ) { fwrite(pDesData, nDesLen, 1, fp); fclose(fp); } } free(pDesData); free(pSrcData); } } //解压文件 LzmaUncompress pLzmaUncom = (LzmaUncompress)GetProcAddress(hModule, "LzmaUncompress"); if ( pLzmaUncom ) { FILE* fp = fopen("c:\\des_7z.dat", "rb"); if ( NULL != fp ) { fseek(fp, 0, SEEK_END); size_t nSrcLen = ftell(fp); fseek(fp, 0, SEEK_SET); byte* pSrcData = (byte*)malloc(nSrcLen); fread(pSrcData, nSrcLen, 1, fp); fclose(fp); size_t nDesLen = 1.1*nSrcLen + 16*1024; byte* pDesData = (byte*)malloc(nDesLen); int nRet = pLzmaUncom(pDesData, &nDesLen, pSrcData, &nSrcLen, prop, nPropSize); if ( SZ_ERROR_INPUT_EOF == nRet ) {//申请空间不足 free(pDesData); pDesData = (byte*)malloc(nDesLen); nRet = pLzmaUncom(pDesData, &nDesLen, pSrcData, &nSrcLen, prop, nPropSize); } if ( SZ_OK == nRet ) {//解压完成 fp = fopen("c:\\out.jpg", "wb+"); if ( NULL != fp ) { fwrite(pDesData, nDesLen, 1, fp); fclose(fp); } } free(pSrcData); free(pDesData); } } FreeLibrary(hModule);涉及到文件读写,内存申请、释放之类的基础就不说了,希望对大家有所帮助。