[英]How to use Poco::ZIP to compress/decompress zip file
我是 C++ 的新手,尤其是在壓縮/解壓縮方面。 我當前的項目使用 Poco 庫,Zip 擴展用於將文件/目錄壓縮或解壓縮為 Zip 文件。
#include <Poco/FileStream.h>
#include <Poco/Zip/Decompress.h>
#include <Poco/Zip/Compress.h>
#include <Poco/Timestamp.h>
#include <Poco/File.h>
voidZipFile(string source, string target, List extensions, bool append, bool overWrite)
{
Poco::DateTime(Timestamp);
set <string> extensionsSet;
std::ofstream fos(target, ios::binary);
Poco::Zip::Compress c(fos, true);
for (int i = 0; i < extensions.Size(); i++) {
string ext = std::dynamic_pointer_cast<String>(extensions.operator[](i))->GetPrimitive();
extensionsSet.insert(ext);
}
c.setStoreExtensions(extensionsSet);//set extensions List
Poco::File aFile(source);//This is where I start my compress action
if (aFile.exists())
{
Poco::Path p(aFile.path());
if (aFile.isDirectory())
{
if (p.isDirectory()) {
c.addDirectory(p, Poco::DateTime());
}
else {
}
}
else if (aFile.isFile())
{
c.addFile(p, p.getFileName());
}
}
else {
_log.EndMethod();
throw new FileNotFoundException("File Not Found");
}
//Poco::FileOutputStream fos(target, std::ios::binary);
c.close(); // MUST be done to finalize the Zip file
fos.close();
}
上面的代碼是我到目前為止所擁有的,我可以將單個文件壓縮為.zip
文件。
如何將文件夾/目錄壓縮為 .zip 文件? 我不能使用另一個庫,因為 Poco 也用於我當前項目的其他部分。
您需要添加一種遞歸方式來搜索文件夾。
這是我想到的:
Poco::File aFile(entry);
if (!aFile.isDirectory())
throw ZipException("Not a directory: "+ entry.toString());
Poco::Path aName(name);
aName.makeDirectory();
if (!excludeRoot)
{
if (aName.depth() == 0)
{
Poco::Path tmp(entry);
tmp.makeAbsolute(); // eliminate ../
aName = Poco::Path(tmp[tmp.depth()-1]);
aName.makeDirectory();
}
addDirectory(aName, aFile.getLastModified());
}
// iterate over children in the directory
std::vector<std::string> children;
aFile.list(children);
std::vector<std::string>::const_iterator it = children.begin();
std::vector<std::string>::const_iterator itEnd = children.end();
for (; it != itEnd; ++it)
{
Poco::Path realFile(entry, *it);
Poco::Path renamedFile(aName, *it);
Poco::File aFile(realFile);
if (aFile.isDirectory())
{
realFile.makeDirectory();
renamedFile.makeDirectory();
addRecursive(realFile, cm, cl, false, renamedFile);
}
else
{
realFile.makeFile();
renamedFile.makeFile();
addFile(realFile, renamedFile, cm, cl);
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.