// stdafx.cpp : 只包括标准包含文件的源文件 // test.pch 将作为预编译头 // stdafx.obj 将包含预编译类型信息 #include "stdafx.h" HMODULE g_hlzma = NULL; lzma_compress g_PtrCompress = NULL; lzma_uncompress g_PtrUnCompress = NULL; BOOL LoadlzmaLibarary() { if ( g_hlzma == NULL ) { g_hlzma = (HMODULE)LoadLibrary(_T("Lzmalib.dll")); if (!g_hlzma) return FALSE; } g_PtrCompress = (lzma_compress)GetProcAddress(g_hlzma, "LzmaCompress"); if ( !g_PtrCompress ) { FreelzmaLibarary(); return FALSE; } g_PtrUnCompress = (lzma_uncompress)GetProcAddress(g_hlzma, "LzmaUncompress"); if ( !g_PtrUnCompress ) { FreelzmaLibarary(); return FALSE; } return TRUE; } void FreelzmaLibarary() { if ( g_hlzma ) { if ( FreeLibrary(g_hlzma) ) { g_hlzma = NULL; g_PtrCompress = NULL; g_PtrUnCompress = NULL; } } } const TCHAR g_szLzma[] = _T("#LZMA#"); BOOL CompressFile(CString strCompressFile) { ////////////////////////////////////////////////////////////////////////// // 压缩文件; ////////////////////////////////////////////////////////////////////////// byte prop[5] = {0}; size_t nPropSize = 5; ULONGLONG ulTickCount = GetTickCount64(); CString strSaveFile = strCompressFile.Mid(0,strCompressFile.ReverseFind('.')) + ".lam"; if ( PathFileExists(strSaveFile) ) { // 已经压缩了; return TRUE; } FILE* fp = fopen(strCompressFile, "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); #ifdef USE_LIB int nRet = LzmaCompress(pDesData, &nDesLen, pSrcData, nSrcLen, prop, &nPropSize, 9, (1<<24), 8, 0, 2, 32, 2); #else int nRet = LzmaCompress(pDesData, &nDesLen, pSrcData, nSrcLen, prop, &nPropSize, 9, (1<<24), 3, 0, 2, 32, 2); #endif if ( SZ_ERROR_OUTPUT_EOF == nRet ) {//申请内存不足; free(pDesData); nDesLen += nSrcLen; pDesData = (byte*)malloc(nDesLen); #ifdef USE_LIB nRet = LzmaCompress(pDesData, &nDesLen, pSrcData, nSrcLen, prop, &nPropSize, 5, (1<<24), 8, 0, 2, 32, 2); #else nRet = LzmaCompress(pDesData, &nDesLen, pSrcData, nSrcLen, prop, &nPropSize, 9, (1<<24), 3, 0, 2, 32, 2); #endif } if ( SZ_OK == nRet ) {//压缩完成,保存文件; fp = fopen(strSaveFile, "wb+"); if ( NULL != fp ) { // 写入压缩标记; fwrite(g_szLzma, strlen(g_szLzma), 1, fp); // 写入prop; fwrite(prop, 5, 1, fp); // 写入nPropSize; fwrite(&nPropSize, sizeof(size_t), 1, fp); // 写入文件大小; fwrite(&nSrcLen, sizeof(size_t), 1, fp); // 写入压缩数据; fwrite(pDesData, nDesLen, 1, fp); fclose(fp); } else { nRet = SZ_ERROR_FAIL; } } free(pDesData); free(pSrcData); if ( nRet != SZ_OK ) return FALSE; } else { return FALSE; } return TRUE; }