简体   繁体   中英

Cpp force write zip using libzip

I am using the header zip.hpp (can be found here https://markand.bitbucket.io/libzip/index.html or here http://hg.markand.fr/libzip/file ) to zip some files.

To remove the raw files afterwards, I use remove("myfile.txt") .

Apparently, zip.hpp zips the files at the end of runtime, thus it cannot find the file and doesnt create a zip-folder. If I leave out remove("myfile.txt") , everything works fine, except for that I have a couple of files flying around that I only want to have in their zipped form.

Do you have any idea on how to force libzip to write the zip-files? I would expect if I delete the archive -instance, it should force the creation, but apparently the libzip::Archive -class doesn't have a destructor (at least I can't find one and delete archive throws many errors)

My basic code looks like this:

#include <fstream>
#include <zip.h>
#include "lib/zip.hpp"


int main () {

    libzip::Archive archive("output.zip", ZIP_CREATE);
    std::ofstream outfile ("myfile.txt");
    outfile << "Hello World\n";
    outfile.close();

    archive.add(libzip::source::file("myfile.txt"), "myfile2.txt");

    // delete archive; // throws an error...

    // remove("myfile.txt"); 
    // if left out, output.zip gets created otherwise nothing is created


    return 0;

}

The libzip::Archive will write its contents when it goes out of scope. So all you need to do is introduce an aditional scope before removing the file.

#include <fstream>
#include <zip.h>
#include "lib/zip.hpp"

int main () {

    { // Additional scope 
        libzip::Archive archive("output.zip", ZIP_CREATE);
        std::ofstream outfile ("myfile.txt");
        outfile << "Hello World\n";
        outfile.close();
        archive.add(libzip::source::file("myfile.txt"), "myfile2.txt");
    } // Archive is written now.

    remove("myfile.txt"); 

    return 0;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM