如何使用 Poco::ZIP 压缩/解压缩 zip 文件

How to use Poco::ZIP to compress/decompress zip file

本文关键字:解压缩 zip 文件 ZIP 何使用 Poco 压缩      更新时间:2023-10-16

我是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);
}
}