How to create an archive of the folder using C++ in Visual Studio 2019, Windows

1.5k Views Asked by At

I wanted to create a Windows Service which copies content of the folder into a created archive. I was suggested to use libzip library for this purpouse. I've created this code, but now I do not know how to compile and link it properly. I am not using CMake for the project building in 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

There are 1 best solutions below

1
Alvov1 On
  1. First of all, it's needed to install libzip package. Easiest way is to install it through the NuGet manager in Visual Studio. Go to Project -> Manage NuGet Packages. Select Browse tab and search for libzip and click install.
  2. After the package is installed, you need to specify libraries location to the linker. It can be done so: Project -> Properties -> Configuration Properties -> Linker -> Input. Select Additional Dependencies on the right. Now you need to add path to the library. NuGet packages are usually installed in C:\Users\...\.nuget\packages. You need to add complete path to the library in double quotes. In my case, it is "C:\Users\...\.nuget\packages\libzip\1.1.2.7\build\native\lib\Win32\v140\Debug\zip.lib".
  3. Now program should compile and link. Upon launch, you may face errors, such as zip.dll or zlibd.dll is missing. For first, copy the zip.dll from libzip.redist package near to the program executable. For second, install zlib from the NuGet