
#include <stdlib.h>
#include <stdio.h>
#include <zlib.h>
int main(int argc, char* argv[])
{
FILE* file
uLong flen
unsigned char* fbuf = NULL
uLong clen
unsigned char* cbuf = NULL
/* 通过命令行参数将srcfile文件的数据压缩后存放到dstfile文件中 */
if(argc < 3)
{
printf("Usage: zcdemo srcfile dstfile\n")
return -1
}
if((file = fopen(argv[1], "rb")) == NULL)
{
printf("Can\'t open %s!\n", argv[1])
return -1
}
/* 装载源文件数据到缓冲区 */
fseek(file, 0L, SEEK_END) /* 跳到文件末尾 */
flen = ftell(file) /* 获取文件长度 */
fseek(file, 0L, SEEK_SET)
if((fbuf = (unsigned char*)malloc(sizeof(unsigned char) * flen)) == NULL)
{
printf("No enough memory!\n")
fclose(file)
return -1
}
fread(fbuf, sizeof(unsigned char), flen, file)
/* 压缩数据 */
clen = compressBound(flen)
if((cbuf = (unsigned char*)malloc(sizeof(unsigned char) * clen)) == NULL)
{
printf("No enough memory!\n")
fclose(file)
return -1
}
if(compress(cbuf, &clen, fbuf, flen) != Z_OK)
{
printf("Compress %s failed!\n", argv[1])
return -1
}
fclose(file)
if((file = fopen(argv[2], "wb")) == NULL)
{
printf("Can\'t create %s!\n", argv[2])
return -1
}
/* 保存压缩后的数据到目标文件 */
fwrite(&flen, sizeof(uLong), 1, file) /* 写入源文件长度 */
fwrite(&clen, sizeof(uLong), 1, file) /* 写入目标数据长度 */
fwrite(cbuf, sizeof(unsigned char), clen, file)
fclose(file)
free(fbuf)
free(cbuf)
return 0
}
Qt调用zlib解压缩的方法
/***返回值:将解压出来的文件的绝对路径保存在QStringList中
*
*参数:FileName是要解压的zip文件的绝对路径,QStringList其实也就是QList<QString> list类型用来保存解压后各文件的路径
*
*功能:解压指定的zip文件并将解压出来的文件的绝对路径保存在list中
**/void WidgetSmallClass::slot_UncompressedFile( QString FileName ,QStringList & ListPic )
{
/**新建一个文件夹,用来保存解压后的文件*/
QString UnpressPath = FileName.remove( ".zip" )
QDir dir
dir.mkpath( UnpressPath )
unz_file_info64 FileInfo
/**打开zip文件,这里记得一定要加上".zip",因为在上面的时候已经将".zip"移出去了。*/
unzFile zFile = unzOpen64( ( FileName + ".zip" ).toStdString().c_str() )
unz_global_info64 gi
/**获取文件数量*/
if ( unzGetGlobalInfo64( zFile, &gi ) == UNZ_OK )
{
int result
for ( int i = 0 i < gi.number_entry ++i )
{
char file[256] = { 0 }
char ext[256] = { 0 }
char com[1024] = { 0 }
if ( unzGetCurrentFileInfo64( zFile, &FileInfo, file, sizeof(file), ext, 256, com, 1024 ) != UNZ_OK )
{
}
if( !( FileInfo.external_fa & FILE_ATTRIBUTE_DIRECTORY ) ) //文件,否则为目录
{
result=unzOpenCurrentFile(zFile)//无密码
result=unzOpenCurrentFilePassword(zFile,"szPassword")//有密码
}
char data[1024] = { 0 }
int size
/**将路径写到list中*/
QString path = UnpressPath + QString ("/") + file
ListPic << path
QFile File( path )
File.open( QFile::WriteOnly )
/**打开新文件并将数据写进去*/
while(true)
{
size= unzReadCurrentFile(zFile,data,sizeof(data))
if(size <= 0) { break }
File.write(data, size)
}
File.close()
unzCloseCurrentFile(zFile)
if( i < gi.number_entry - 1 && unzGoToNextFile( zFile ) != UNZ_OK ) { return }
}
unzClose(zFile)
}
else { return }
}
欢迎分享,转载请注明来源:内存溢出
微信扫一扫
支付宝扫一扫
评论列表(0条)