Rahul Kumar
Rahul Kumar

Reputation: 348

Writing file inside zip using libzip

I am using libzip android port from here. I am able to add a new file in my archive calling zip_add(_zip, filePath, zip_source_callback). it creates an empty file. How can i write data to this empty file?

I know i have to handle it in my zip_source_callback method but i don't know exactly what and how. Any help will be appreciated.

my zip_source_callback looks like this for now:

ssize_t  _source_callback(void *state, void *data, size_t len, enum zip_source_cmd cmd)
{
    ssize_t r = 0;
    switch ( cmd )
    {
        case ZIP_SOURCE_OPEN:
        {
            LOGD("ZIP_SOURCE_OPEN");
            break;
        }
        case ZIP_SOURCE_CLOSE:
        {
            LOGD("ZIP_SOURCE_CLOSE");
            break;
        }
        case ZIP_SOURCE_STAT:
        {
            LOGD("ZIP_SOURCE_STAT");
            break;
        }
        case ZIP_SOURCE_ERROR:
        default:
        {
            LOGD("ZIP_SOURCE_ERROR");
            break;
        }
        case ZIP_SOURCE_READ:
        {
            LOGD("ZIP_SOURCE_READ");
            break;
        }
        case ZIP_SOURCE_FREE:
        {
            LOGD("ZIP_SOURCE_FREE");
            return 0;
        }
    }
    return r;
}

Upvotes: 2

Views: 1143

Answers (1)

RyanCu
RyanCu

Reputation: 566

You don't need to use zip_source_callback if the data you want to add is a contiguous block of memory; you can use zip_source_buffer to create the zip_source_t you need, which is simpler. There is an example of how to use zip_source_buffer at https://libzip.org/documentation/zip_file_add.html

Here I've adapted their example for adding the memory in a std::vector called dataVector. This code would be placed between the code opening and closing the zip archive.

zip_source_t *source;
if ((source=zip_source_buffer(archive, dataVector.data(), dataVector.size(), 0)) == nullptr ||
    zip_file_add(archive, name, source, ZIP_FL_ENC_UTF_8) < 0) {
        zip_source_free(source);
        printf("error adding file: %s\n", zip_strerror(archive));
}

Upvotes: 1

Related Questions