在C目录中有算法文件,进入Util\LzmaLib目录,编译生成LIB库,导出了以下两函数,LzmaCompress 为压缩函数,LzmaUncompress 为解压缩函数。
MY_STDAPI LzmaCompress(unsigned char *dest, size_t *destLen, const unsigned char *src, size_t srcLen,
unsigned char *outProps, size_t *outPropsSize,
int level,
unsigned dictSize,
int lc,
int lp,
int pb,
int fb,
int numThreads
);
MY_STDAPI LzmaUncompress(unsigned char *dest, size_t *destLen, const unsigned char *src, SizeT *srcLen,
const unsigned char *props, size_t propsSize);
导入Types.h 和 Lzmalib.h 到工程中。
代码如下:
#include "stdafx.h"
#include "LzmaLib.h"
#pragma comment(lib,"lzma.lib")
int _tmain(int argc, _TCHAR* argv[])
{
FILE* pFile = _tfopen(_T("file.dat"), _T("rb"));
if (pFile == NULL)
{
_ftprintf(stderr, _T("Error to Open the file!"));
return - 1;
}
fseek(pFile, 0, SEEK_END);
size_t srcLen = ftell(pFile);
rewind(pFile);
size_t destLen = srcLen * 2;
unsigned char* psrcRead = new unsigned char[srcLen]; //原始文件数据
unsigned char* pDecomress = new unsigned char[srcLen]; //存放解压缩数据
unsigned char* pLzma = new unsigned char[destLen]; //存放压缩数据
fread(psrcRead, sizeof(char), srcLen, pFile);
unsigned char prop[5] =
{
0
};
size_t sizeProp = 5;
if (SZ_OK != LzmaCompress(pLzma, &destLen, psrcRead, srcLen, prop,
&sizeProp, 9, (1 << 24), 3, 0, 2, 32, 2))
{
//出错了
_ftprintf(stderr, _T("压缩时出错!"));
delete [] psrcRead;
delete [] pDecomress;
delete [] pLzma;
fclose(pFile);
return - 1;
}
FILE* pCompressFile = _tfopen(_T("compress.dat"), _T("wb"));
//写入压缩后的数据
if (pCompressFile == NULL)
{
_ftprintf(stderr, _T("创建文件出错!"));
delete [] psrcRead;
delete [] pDecomress;
delete [] pLzma;
fclose(pFile);
return - 1;
}
fwrite(pLzma, sizeof(char), destLen, pCompressFile);
fclose(pCompressFile);
FILE* pDecompressFile = _tfopen(_T("decompress.dat"), _T("wb"));
//写入解压缩数据
if (pDecompressFile == NULL)
{
_ftprintf(stderr, _T("写入数据出错!"));
delete [] psrcRead;
delete [] pDecomress;
delete [] pLzma;
fclose(pFile);
return - 1;
}
//注意:解压缩时props参数要使用压缩时生成的outProps,这样才能正常解压缩
if (SZ_OK != LzmaUncompress(pDecomress, &srcLen, pLzma, &destLen, prop, 5))
{
delete [] psrcRead;
delete [] pDecomress;
delete [] pLzma;
fclose(pDecompressFile);
fclose(pFile);
return - 1;
}
fwrite(pDecomress, sizeof(char), srcLen, pDecompressFile);
delete [] psrcRead;
delete [] pDecomress;
delete [] pLzma;
fclose(pDecompressFile);
fclose(pFile);
return 0;
}