要实现压缩和解压功能,可以使用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文件,解压出文本文件并保存到磁盘上。这样就完成了一个简单的压缩和解压的功能。