zip学习笔记 —— 用C编写的简单压缩库

一、简介

基于 miniz 的用C语言编写的可移植的、简单的 zip 库。Miniz 是一个无损的、高性能的数据压缩库,位于一个源文件中。只需要简单的接口来附加缓冲区或文件到当前的 zip 条目。

二、移植

项目地址:https://github.com/kuba–/zip

miniz.hzip.czip.h 加入工程中

三、示例

3.1 创建一个具有默认压缩级别的新压缩存档

struct zip_t *zip = zip_open("foo.zip", ZIP_DEFAULT_COMPRESSION_LEVEL, 'w');
{
    
    
    zip_entry_open(zip, "foo-1.txt");
    {
    
    
        const char *buf = "Some data here...\0";
        zip_entry_write(zip, buf, strlen(buf));
    }
    zip_entry_close(zip);

    zip_entry_open(zip, "foo-2.txt");
    {
    
    
        // merge 3 files into one entry and compress them on-the-fly.
        zip_entry_fwrite(zip, "foo-2.1.txt");
        zip_entry_fwrite(zip, "foo-2.2.txt");
        zip_entry_fwrite(zip, "foo-2.3.txt");
    }
    zip_entry_close(zip);
}
zip_close(zip);

3.2 解压缩到文件夹中

int on_extract_entry(const char *filename, void *arg) {
    
    
    static int i = 0;
    int n = *(int *)arg;
    printf("Extracted: %s (%d of %d)\n", filename, ++i, n);

    return 0;
}

int arg = 2;
zip_extract("foo.zip", "/tmp", on_extract_entry, &arg);

3.3 将压缩条目解压缩到内存中

void *buf = NULL;
size_t bufsize;

struct zip_t *zip = zip_open("foo.zip", 0, 'r');
{
    
    
    zip_entry_open(zip, "foo-1.txt");
    {
    
    
        zip_entry_read(zip, &buf, &bufsize);
    }
    zip_entry_close(zip);
}
zip_close(zip);

free(buf);

• 由 Leung 写于 2020 年 9 月 21 日

• 参考:https://github.com/kuba–/zip

猜你喜欢

转载自blog.csdn.net/qq_36347513/article/details/108709366
今日推荐