对于文件的压缩和解压是我们日常工作耳熟能详的操作,那么我们如何自己通过代码来实现各种文件的压缩和解压,本文是笔者整理和精炼的的7zipSDK,支持zip,rar,7zip,tar,xz等常见格式的压缩和解压,接口友好,demo简单,特意收藏,以备不时之需。
压缩例子如下:
#include <iostream>
#include<string>
#include "7zpp.h"
#define DLL_PATH _T("C:\\Program Files\\7-Zip\\7z.dll")
#define TESTCOMPRESSTESTFILE1 _T("TestFiles\\Readme.md")
#define TESTEXTRACTTESTFILE2 _T("TestFiles\\dir")
#define ARCHIVE_NAME1 _T("MyArchive")
using namespace std;
using namespace SevenZip;
void comprese_file(SevenZip::CompressionFormat::_Enum fmt)
{
SevenZip::SevenZipLibrary lib;
bool result = lib.Load(SevenZip::TString(DLL_PATH));
// Make sure DLL loads
if (!result)
{
printf("load dll is failed\n");
}
printf("CompressionFormat is %d\n", fmt);
SevenZip::TString myArchive(ARCHIVE_NAME1);
SevenZip::SevenZipCompressor compressor(lib, myArchive);
compressor.SetCompressionFormat(fmt);
compressor.SetPassword(_T("test"));
bool addResult = compressor.AddFile(TESTCOMPRESSTESTFILE1);
if (!result)
{
printf("AddFile is failed\n");
}
// add files by mask non recursive in folder where no files with this mask
addResult = compressor.AddFiles(TESTEXTRACTTESTFILE2, _T("*.h"), false);
if (!result)
{
printf("AddFile2 is failed\n");
}
addResult = compressor.AddFiles(TESTEXTRACTTESTFILE2, _T("*.h"), true);
if (!result)
{
printf("AddFile3 is failed\n");
}
bool compressResult = compressor.DoCompress();
if (!result)
{
printf("AddFile4 is failed\n");
}
getchar();
}
int main()
{
std::cout << "Hello World!\n";
comprese_file(SevenZip::CompressionFormat::SevenZip);
}
解压文件例子
例子如下:
#include <iostream>
#include<string>
#include "7zpp.h"
#define DLL_PATH _T("C:\\Program Files\\7-Zip\\7z.dll")
#define TESTEXTRACTTESTFILE1 _T("TestFiles\\dir.7z")
#define TESTEXTRACTTESTTMP _T("TestFiles\\temp")
using namespace std;
using namespace SevenZip;
void Extration_file( SevenZip::CompressionFormat::_Enum fmt)
{
SevenZip::SevenZipLibrary lib;
bool result = lib.Load(SevenZip::TString(DLL_PATH));
if (!result)
{
printf("load dll is failed\n");
return;
}
printf("CompressionFormat is %d\n",fmt);
SevenZip::TString myArchive(TESTEXTRACTTESTFILE1);
SevenZip::TString myDest(TESTEXTRACTTESTTMP);
//
// Extract
//
SevenZip::SevenZipExtractor extractor(lib, myArchive);
//
// Try to detect compression format, num of items, and names
//
SevenZip::CompressionFormatEnum myCompressionFormat;
// Read in all the metadata
extractor.ReadInArchiveMetadata();
// Pull the metadata locally
myCompressionFormat = extractor.GetCompressionFormat();
//
// Using callbacks
//
extractor.SetCompressionFormat(fmt);
result = extractor.ExtractArchive(myDest, nullptr);
if (!result)
{
printf("ExtractArchive is failed\n");
return;
}
}
int main()
{
std::cout << "Hello World!\n";
Extration_file(SevenZip::CompressionFormat::SevenZip);
getchar();
}
以上只是文件压缩和解压的基本例子,该SDK还支持文件列表查看,内存数据压缩成文件等。