如何在Visual Studio 2019 Windows中使用C++创建文件夹的存档



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

#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.7buildnativelibWin32v140Debugzip.lib"
  3. 现在程序应该编译并链接。启动后,您可能会遇到错误,例如zip.dllzlibd.dll丢失。首先,从程序可执行文件附近的libzip.redist包中复制zip.dll。第二,从NuGet安装zlib

最新更新