1

我想创建一个 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;
}
4

1 回答 1

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\...\.nuget\packages. 您需要在双引号中添加库的完整路径。就我而言,它是"C:\Users\...\.nuget\packages\libzip\1.1.2.7\build\native\lib\Win32\v140\Debug\zip.lib".
  3. 现在程序应该编译和链接。启动时,您可能会遇到错误,例如丢失zip.dllzlibd.dll丢失。首先,将压缩包中的 zip.dll 复制libzip.redist到程序可执行文件附近。其次,从 NuGet 安装 zlib
于 2022-01-06T17:35:09.317 回答