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

标签 c++ poco-libraries

我正在构建一个压缩/解压缩功能,目前,我只能将 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/

相关文章:

c++ - 在 Linux 上使用 poco 卸载库失败

c++ - Clang 拒绝编译 libstdc++ 的 <filesystem> header

c++ - QWidgetAction 在 trigger() 之后保持可见

c++ - 在 Visual Studio 2008 中设置 Win32 DLL

c++ - 哪个 C++ IDE 支持快速 TDD 工作流程和 Google 或 Boost 测试框架?

c++ - MFC 全局键盘 Hook

c++ - Poco Http 响应未正确解码

c++ - 从一对中获取值失败,错误为 : TYPENAME does not provide a call operator

c++ - Poco - 设置无限套接字接收超时

c++ - Poco 时间戳和时间跨度