'How to create an archive of the folder using C++ in Visual Studio 2019, Windows
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;
}
Solution 1:[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. SelectBrowsetab and search for libzip and clickinstall. - 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.SelectAdditional Dependencieson the right. Now you need to add path to the library. NuGet packages are usually installed inC:\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". - Now program should compile and link. Upon launch, you may face errors, such as
zip.dllorzlibd.dllis missing. For first, copy the zip.dll fromlibzip.redistpackage near to the program executable. For second, install zlib from the NuGet
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Alvov1 |
