使用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)以便拉您進羣。