对于文件的压缩和解压是我们日常工作耳熟能详的操作,那么我们如何自己通过代码来实现各种文件的压缩和解压,本文是笔者整理和精炼的的7zipSDK,支持zip,rar,7zip,tar,xz等常见格式的压缩和解压,接口友好,demo简单,特意收藏,以备不时之需。
压缩例子如下:
代码语言:javascript复制#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 failedn");
}
printf("CompressionFormat is %dn", 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 failedn");
}
// 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 failedn");
}
addResult = compressor.AddFiles(TESTEXTRACTTESTFILE2, _T("*.h"), true);
if (!result)
{
printf("AddFile3 is failedn");
}
bool compressResult = compressor.DoCompress();
if (!result)
{
printf("AddFile4 is failedn");
}
getchar();
}
int main()
{
std::cout << "Hello World!n";
comprese_file(SevenZip::CompressionFormat::SevenZip);
}
解压文件例子
例子如下:
代码语言:javascript复制#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 failedn");
return;
}
printf("CompressionFormat is %dn",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 failedn");
return;
}
}
int main()
{
std::cout << "Hello World!n";
Extration_file(SevenZip::CompressionFormat::SevenZip);
getchar();
}
以上只是文件压缩和解压的基本例子,该SDK还支持文件列表查看,内存数据压缩成文件等。更多更详细信息请关注公众号:AV_Chat,该SDK下载地址
https://download.csdn.net/download/fengliang191/13981776