Reputation: 79
I'm trying to unzip an executable file using c++ and the libzip library. Starting with the answer by rodrigo on a similar question, I come to this sample code:
#include <zip.h>
int main()
{
//Open the ZIP archive
int err = 0;
zip *z = zip_open("foo.zip", 0, &err);
//Search for the file of given name
const char *name = "file.txt";
struct zip_stat st;
zip_stat_init(&st);
zip_stat(z, name, 0, &st);
//Alloc memory for its uncompressed contents
char *contents = new char[st.size];
//Read the compressed file
zip_file *f = zip_fopen(z, "file.txt", 0);
zip_fread(f, contents, st.size);
zip_fclose(f);
//And close the archive
zip_close(z);
}
from what I understand, this code does work to unzip a file, but I do not know how to write that file to the disk, much like extracting a zip file would so using a tool like winzip does. Having the unzipped data in memory doesn't help me, but I've been unable to figure out how to actually get the files onto the disk.
Upvotes: 6
Views: 6554
Reputation: 48605
Something like this should do it:
if(!std::ofstream("file1.txt").write(contents, st.size))
{
std::cerr << "Error writing file" << '\n';
return EXIT_FAILURE;
}
Look up std::ofstream.
Of course you should check all your zip
file functions to see if they returned errors before proceeding.
Upvotes: 3