《Coding Art》第19篇 zip files by c in linux

使用C语言将多个文件压缩到一个zip文件的方法。

1. 首先安装libzip库

sudo apt install libzip-dev

查看版本(ubuntu 24的版本为1.7.3)

apt show libzip-dev

2. 然后查看libzip的文档(文档版本是1.11.2,比安装的版本高,因此有些东西不一致)

https://libzip.org/documentation/zip_open.html

https://libzip.org/documentation/zip_source_file.html

https://libzip.org/documentation/zip_file_add.html


 

3. 参考使用gemini提供的例子


#include <zip.h>

#include <stdio.h>

#include <stdlib.h>

#include <string.h>



// zip_path 是最终生成的.zip文件的路径

// file_list是文件名列表, file_list_len是列表的长度

// parent_path是文件所在的文件夹的路径,注意要以/结尾

const char* file_make_zip(const char* zip_path, const char** file_list, int32_t file_list_len, const char* parent_path)

{

zip_t *zip = zip_open(zip_path, ZIP_CREATE | ZIP_TRUNCATE, NULL); if (!zip) { printf("make zip file error: %s", zip_path); return NULL; }

size_t parent_path_len=strlen(parent_path); for(int32_t i=0;i<file_list_len;i++)

{

const char* item_name=file_list[i]; size_t item_path_size=parent_path_len + strlen(item_name) + 1; char* item_path=malloc(item_path_size); snprintf(item_path, item_path_size, "%s%s", parent_path, item_name);

zip_source_t * zip_source = zip_source_file(zip, item_path, 0, 0); if(zip_source==NULL){ printf("make zip item source error: %s", item_path); return NULL; }

if(zip_file_add(zip, item_name, zip_source, ZIP_FL_ENC_UTF_8)<0){ zip_source_free(zip_source); printf("add zip item error: %s", item_path); return NULL; }

}

zip_close(zip); return zip_path;

}


4. 编译的时候添加 -lzip 库。

参考资料:

gemini ai

https://www.cnblogs.com/charlee44/p/18299531

如果您對C語言編程、網站開發、Vue, Git, Linux, Shell感興趣,邀請您加入淨明創建的「Linux + C語言 + Vue + Git 網站開發技術學習交流微信羣」,請加淨明的微信(si_jinmin)以便拉您進羣。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

qiuzen

您的资助将帮助我创作更好的作品

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值