2

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;
}
Rahul Kumar
  • 340
  • 1
  • 3
  • 12
  • 1
    `zip_add` is deprecated. The functions to use are outlined at https://libzip.org/documentation/libzip.html – RyanCu Jun 05 '19 at 08:48
  • What is the source of the data you want to add? Is it a file on disk, a block of data in memory, or can the data be generated piecemeal via function calls? – RyanCu Jun 05 '19 at 08:49
  • @RyanCu data is generated on run time and is in a vector variable – Rahul Kumar Jul 02 '19 at 14:51

1 Answers1

1

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));
}
RyanCu
  • 516
  • 4
  • 12