如何在Visual Studio 2019 Windows中使用C++创建文件夹存档 [英] How to create an archive of the folder using C++ in Visual Studio 2019, Windows

查看:176
本文介绍了如何在Visual Studio 2019 Windows中使用C++创建文件夹存档的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想创建一个Windows服务,将文件夹内容复制到创建的存档中。有人建议我在这个地方使用libzip库。我已经创建了这段代码,但是现在我不知道如何正确编译和链接它。我没有将CMake用于Visual Studio中的项目生成。

#include <iostream>
#include <filesystem>
#include <string>
#include <zip.h>

constexpr auto directory = "C:/.../Directory/";
constexpr auto archPath = "C:/.../arch.zip";

int Archive(const std::filesystem::path& Directory, const std::filesystem::path& Archive) {
    int error = 0;
    zip* arch = zip_open(Archive.string().c_str(), ZIP_CREATE, &error);
    if (arch == nullptr)
        throw std::runtime_error("Unable to open the archive.");


    for (const auto& file : std::filesystem::directory_iterator(Directory)) {
        const std::string filePath = file.path().string();
        const std::string nameInArchive = file.path().filename().string();

        auto* source = zip_source_file(arch, item.path().string().c_str(), 0, 0);
        if (source == nullptr)
            throw std::runtime_error("Error with creating source buffer.");

        auto result = zip_file_add(arch, nameInArchive.c_str(), source, ZIP_FL_OVERWRITE);
        if (result < 0)
           throw std::runtime_error("Unable to add file '" + filePath + "' to the archive.");
    }

    zip_close(arch);
    return 0;
}
int main() {
    std::filesystem::path Directory(directory);
    std::filesystem::path ArchiveLocation(archPath);

    Archive(Directory, ArchiveLocation);
    return 0;
}

推荐答案

  1. 首先需要安装libzip包。最简单的方法是通过Visual Studio中的NuGet管理器安装它。转到Project -> Manage NuGet Packages。选择Browse选项卡并搜索libzip,然后单击install
  2. 安装包后,需要指定链接器的库位置。可以这样做:Project -> Properties -> Configuration Properties -> Linker -> Input.选择右侧的Additional Dependencies。现在您需要添加库的路径。Nuget包通常安装在C:Users....nugetpackages中。您需要将库的完整路径添加到双引号中。在我的情况下,它是"C:Users....nugetpackageslibzip1.1.2.7uild ativelibWin32v140Debugzip.lib"
  3. 现在程序应该编译并链接。启动时可能会出现错误,例如缺少zip.dllzlibd.dll。首先,从程序可执行文件附近的libzip.redist包复制zip.dll。第二,从NuGet安装zlib

这篇关于如何在Visual Studio 2019 Windows中使用C++创建文件夹存档的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆