PS; zlib库比较老了,好像是Version 1.01e。基本功能也差不多。
part1:
使用codeproject上的完整的库,大牛弄的是真的方便简单。
地址:http://www.codeproject.com/Articles/7530/Zip-Utils-clean-elegant-simple-C-Win
下载下来就四个文件,zip.h zip.cpp unzip.h unzip.cpp
使用的时候直接include就行了。
直接贴上面的readme吧。
For unzipping, add "unzip.cpp" to your project. Then, for example,
#include "unzip.h"
//
HZIP hz = OpenZip("c:\\stuff.zip",0);
ZIPENTRY ze; GetZipItem(hz,-1,&ze); int numitems=ze.index;
for (int i=0; i<numitems; i++)
{ GetZipItem(hz,i,&ze);
UnzipItem(hz,i,ze.name);
}
CloseZip(hz);
For zipping, add "zip.cpp" to your project. (You can add just one of
zip/unzip, or both; they function independently and also co-exist.)
#include "zip.h"
//
HZIP hz = CreateZip("c:\\simple1.zip",0);
ZipAdd(hz,"znsimple.bmp", "c:\\simple.bmp");
ZipAdd(hz,"znsimple.txt", "c:\\simple.txt");
CloseZip(hz);
part2: 使用zlib 老牌的库了
上代码:
直接把添加压缩的封装好了;
void AddFileToZip(zipFile zf, const char* fileNameInZip, const char* srcFile)
{
FILE* srcfp = NULL;
//初始化写入zip的文件信息
zip_fileinfo zi;
zi.tmz_date.tm_sec = zi.tmz_date.tm_min = zi.tmz_date.tm_hour =
zi.tmz_date.tm_mday = zi.tmz_date.tm_mon = zi.tmz_date.tm_year = 0;
zi.dosDate = 0;
zi.internal_fa = 0;
zi.external_fa = 0;
//如果srcFile为空,加入空目录
char new_file_name[WRITEBUFFERSIZE];
memset(new_file_name, 0, sizeof(new_file_name));
strcat(new_file_name, fileNameInZip);
if (srcFile == NULL)
{
strcat(new_file_name, "/");
}
//在zip文件中创建新文件
zipOpenNewFileInZip(zf, new_file_name, &zi, NULL, 0, NULL, 0, NULL, Z_DEFLATED, Z_DEFAULT_COMPRESSION);
if (srcFile != NULL)
{
//打开源文件
srcfp = fopen(srcFile, "rb");
if (srcfp == NULL)
{
zipCloseFileInZip(zf); //关闭zip文件
return;
}
//读入源文件并写入zip文件
int size_buf = 0;
void* buf=NULL;
size_buf = WRITEBUFFERSIZE;
buf = (void*)malloc(size_buf);
int numBytes = 0;
while( !feof(srcfp) )
{
numBytes = fread(buf, 1, size_buf, srcfp);
zipWriteInFileInZip(zf, buf, numBytes);
if( ferror(srcfp) )
break;
}
//关闭源文件
fclose(srcfp);
}
//关闭zip文件
zipCloseFileInZip(zf);
}
使用时候:
zipFile zf;
AddFileToZip(zf,"zip里的名字","需要压缩的源文件");
zipClose(zf,0);
暂时没有弄,压缩到zip文件夹和解压部分。以后再添加