要實現壓縮和解壓功能,可以使用minizip庫提供的函數來完成。以下是一個簡單的示例代碼,展示了如何使用minizip庫來進行壓縮和解壓:
#include <stdio.h>
#include "zip.h"
#include "unzip.h"
int main() {
const char* zipfilename = "example.zip";
const char* filename = "example.txt";
// 壓縮文件
zipFile zf = zipOpen(zipfilename, 0);
if (zf == NULL) {
fprintf(stderr, "Error opening %s\n", zipfilename);
return -1;
}
FILE* fin = fopen(filename, "rb");
if (fin == NULL) {
fprintf(stderr, "Error opening %s\n", filename);
return -1;
}
zip_fileinfo zi;
memset(&zi, 0, sizeof(zip_fileinfo));
zipOpenNewFileInZip(zf, "example.txt", &zi, NULL, 0, NULL, 0, NULL, Z_DEFLATED, Z_DEFAULT_COMPRESSION);
char buf[1024];
int size;
while ((size = fread(buf, 1, sizeof(buf), fin)) > 0) {
zipWriteInFileInZip(zf, buf, size);
}
fclose(fin);
zipCloseFileInZip(zf);
zipClose(zf, NULL);
// 解壓文件
unzFile uf = unzOpen(zipfilename);
if (uf == NULL) {
fprintf(stderr, "Error opening %s\n", zipfilename);
return -1;
}
unz_file_info file_info;
if (unzLocateFile(uf, "example.txt", 0) != UNZ_OK) {
fprintf(stderr, "File not found in zip\n");
return -1;
}
if (unzOpenCurrentFile(uf) != UNZ_OK) {
fprintf(stderr, "Error opening current file\n");
return -1;
}
FILE* fout = fopen("example_unzipped.txt", "wb");
if (fout == NULL) {
fprintf(stderr, "Error opening output file\n");
return -1;
}
while ((size = unzReadCurrentFile(uf, buf, sizeof(buf))) > 0) {
fwrite(buf, 1, size, fout);
}
fclose(fout);
unzCloseCurrentFile(uf);
unzClose(uf);
return 0;
}
在這個示例中,我們首先打開一個zip文件,然后將一個文本文件壓縮到zip文件中。接著,我們再打開這個zip文件,解壓出文本文件并保存到磁盤上。這樣就完成了一個簡單的壓縮和解壓的功能。