To get started with libzip, I tried to create an archive and add a file to it. This is my code.
string archive = "path/to/archive.zip";
string file = "message";
char *data = "Hello World!";
int error = 0;
zip *archive = zip_open(path.c_str(), ZIP_CREATE, &error);
if(error)
{
cout << "could not open or create archive" << endl;
return false;
}
zip_source *source = zip_source_buffer(archive, data, sizeof(data), 0);
if(source == NULL)
{
cout << "failed to create source buffer. " << zip_strerror(archive) << endl;
return false;
}
int index = (int)zip_file_add(archive, file.c_str(), source, ZIP_FL_OVERWRITE);
if(index < 0)
{
cout << "failed to add file to archive. " << zip_strerror(archive) << endl;
return false;
}
zip_source_free(source);
zip_close(archive);
return true;
This code throws a runtime error at the zip_close()
call.
Unhandled exception at 0x00EDDD16 in Application.exe: 0xC00000FD: Stack overflow (parameters: 0x00000001, 0x002C2FFC).
Update: I removed the zip_source_free()
call since I was told that this is already done by zip_file_add()
. Moreover, I check archive
to not hold NULL
. These changes raised another error at zip_close()
.
Unhandled exception at 0x0065BC57 in Application.exe: An invalid parameter was passed to a function that considers invalid parameters fatal.
What am I doing wrong?
You should not call zip_source_free()
since source
has already been used in zip_file_add()
and freed there.
Also, you should check the return value of zip_open()
instead of the value of errorp
. Nothing in the documentation indicates that error codes are different than 0. However, the return value will be NULL
if the zip file cannot be opened.