gpt4 book ai didi

c++ - 使用 Poco::zip 添加新目录总是给出异常

转载 作者:行者123 更新时间:2023-12-02 10:37:45 28 4
gpt4 key购买 nike

我正在构建一个压缩/解压缩功能,目前,我只能将 1 个单个文件压缩成一个 zip 文件。每次我添加一个新目录或递归添加一个目录时,它总是给我异常(exception)。

这是我的ZipFile功能:

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);

if (aFile.exists())
{
Poco::Path p(aFile.path());
if (aFile.isDirectory())
{
Poco::Path sourceDir(source);
Poco::Path targetDir(target);
c.addDirectory(targetDir, Poco::DateTime(Timestamp));// give exception
targetDir.makeDirectory();
c.addRecursive(sourceDir);
}
else if (aFile.isFile())
{
c.addFile(p, p.getFileName());
}
}
else {
_log.EndMethod();
throw new FileNotFoundException("File Not Found");
}


c.close(); // MUST be done to finalize the Zip file
fos.close();

这是我的异常(exception),下面的代码块在 Poco 的 addDirectory 方法中:
if (!ZipCommon::isValidPath(fileStr))
throw ZipException("Illegal entry name " + fileStr + " containing parent directory reference");

最佳答案

“Poco::Path”中有一个成员叫做“absolute”。
您可以通过构造函数将 absolute 设置为 false

否则会抛出 ZipException,因为此函数返回“false”:

bool ZipCommon::isValidPath(const std::string& path)
{
try
{
if (Path(path, Path::PATH_UNIX).isAbsolute() || Path(path, Path::PATH_WINDOWS).isAbsolute())
return false;
}
...
}

这是一个例子:
std::ofstream fos(target, ios::binary);
Poco::Zip::Compress compress(fos, true);
std::vector<std::string> dirs; // parent dirs in zip file
Poco::Path myPath(false); // set path to non-absolute

// add parent directories
for (auto& dir : dirs)
{
myPath.pushDirectory(dir);
}

//add file
myPath.setFileName("FileName.txt");

//add file to archive
compress.addFile(theFile, relativePath);

//close archive and get zipArchiveObject
ZipArchive zipArchive(compress.close());

关于c++ - 使用 Poco::zip 添加新目录总是给出异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59527408/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com