Qt调用zlib解压缩的方法
/**
*返回值:将解压出来的文件的绝对路径保存在QStringList中
*
*参数:FileName是要解压的zip文件的绝对路径,QStringList其实也就是QList<QString>list类型用来保存解压后各文件的路径
*
*功能:解压指定的zip文件并将解压出来的文件的绝对路径保存在list中
**/voidWidgetSmallClass::slot_UncompressedFile(QStringFileName,QStringList&ListPic)
{
/**新建一个文件夹,用来保存解压后的文件*/
QStringUnpressPath=FileName.remove(".zip");
QDirdir;
dir.mkpath(UnpressPath);
unz_file_info64FileInfo;
/**打开zip文件,这里记得一定要加上".zip",因为在上面的时候已经将".zip"移出去了。*/
unzFilezFile=unzOpen64((FileName+".zip").toStdString().c_str());
unz_global_info64gi;
/**获取文件数量*/
if(unzGetGlobalInfo64(zFile,&gi)==UNZ_OK)
{
intresult;
for(inti=0;i<gi.number_entry;++i)
{
charfile[256]={0};
charext[256]={0};
charcom[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");//有密码
}
chardata[1024]={0};
intsize;
/**将路径写到list中*/
QStringpath=UnpressPath+QString("/")+file;
ListPic<<path;
QFileFile(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; }
}
⑵ 如何使用Zlib解压内存块中的文件
1 准备工作。 下载zlib.dll。以及相关头文件。将dll文件及头文件加入工程。 2 压缩: 调用函数compress. 形式为 int compress(Byte * dest, uLong* destLen, const Byte *source, ULONG sourceLen); 功能是将source指向的空间,长度为sourceLen的数据进行压缩,压缩数据储存在dest中,长度由参数destLen返回。 如果压缩出错,返回对应错误号,否则返回0. 3解压缩: 调用函数uncompress. 形式为 int uncompress(Byte * dest, uLong* destLen, const Byte *source, ULONG sourceLen); 功能是将source指向的空间,长度为sourceLen的数据进行解压缩,解压缩后的数据储存在dest中,长度由参数destLen返回。 如果解压缩出错,返回对应错误号,否则返回0.
⑶ 怎么用zlib生成标准zip压缩文件和解压缩zip文件
你用的是什么压缩软件?7-Zip? rar是Winrar的私有格式,其它压缩软件通常只能打开和解压缩,而不能生成(否则必须得到Winrar的授权)。 其它你用7z格式就可以了,Winrar等都可以打开7z(7-Zip是开源软件)。你发给别人7z格式,他不论装什么压缩.
⑷ delphi中用zlib怎样压缩和解压
数据压缩和解压的示例代码:
{压缩流}
function CompressStream(ASrcStream: TStream; ALevel: TSfCompressionLevel): TStream;
var
SrcData,Buffer:Pointer;
BufSize:Integer;
begin
Buffer:=nil;
Result:=nil;
BufSize:=0;
GetMem(SrcData,ASrcStream.Size);
ASrcStream.Position:=0;
ASrcStream.Read(SrcData^,ASrcStream.Size);
try
try
SfCompressBuf(SrcData,ASrcStream.Size,Buffer,BufSize,ALevel);
except
on E:Exception do
SfRaiseException(E,'Exception raised in CompressStream call');
end;
finally
FreeMem(SrcData);
SrcData:=nil;
end;
//由于try...except块中重引发了异常,所以在发生了异常的情况下,以下的代码不会执行
Result:=TMemoryStream.Create;
Result.Write(Buffer^,BufSize);
FreeMem(Buffer);
end;
{解压流}
function CompressStream(ASrcStream: TStream; ALevel: TSfCompressionLevel): TStream;
var
SrcData,Buffer:Pointer;
BufSize:Integer;
begin
Buffer:=nil;
Result:=nil;
BufSize:=0;
GetMem(SrcData,ASrcStream.Size);
ASrcStream.Position:=0;
ASrcStream.Read(SrcData^,ASrcStream.Size);
try
try
SfCompressBuf(SrcData,ASrcStream.Size,Buffer,BufSize,ALevel);
except
on E:Exception do
SfRaiseException(E,'Exception raised in CompressStream call');
end;
finally
FreeMem(SrcData);
SrcData:=nil;
end;
//由于try...except块中重引发了异常,所以在发生了异常的情况下,以下的代码不会执行
Result:=TMemoryStream.Create;
Result.Write(Buffer^,BufSize);
FreeMem(Buffer);
end;
{压缩字节数组}
function CompressBytes(ASrcBytes: TBytes; ALevel: TSfCompressionLevel): TBytes;
var
Buffer:Pointer;
BufSize:Integer;
begin
Buffer:=nil;
BufSize:=0;
try
SfCompressBuf(@ASrcBytes[0],Length(ASrcBytes),Buffer,BufSize,ALevel);
SetLength(Result,BufSize);
Move(Buffer^,Result[0],BufSize);
except
on E:Exception do
SfRaiseException(E,'Exception raised in CompressBytes call');
end;
//由于try...except块中重引发了异常,所以在发生了异常的情况下,以下的代码不会执行
FreeMem(Buffer);
end;
{解压字节数组}
function DecompressBytes(ASrcBytes: TBytes): TBytes;
var
Buffer:Pointer;
BufSize:Integer;
begin
Buffer:=nil;
BufSize:=0;
try
SfDecompressBuf(@ASrcBytes[0],Length(ASrcBytes),0,Buffer,BufSize);
SetLength(Result,BufSize);
Move(Buffer^,Result[0],BufSize);
except
on E:Exception do
SfRaiseException(E,'Exception raised in DecompressBytes call');
end;
//由于try...except块中重引发了异常,所以在发生了异常的情况下,以下的代码不会执行
FreeMem(Buffer);
end;
⑸ C++语言怎么用zlib库来解压.ISO或.zip文件
下面是使用zlib库的压缩和解压缩演示代码:
#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;
}
⑹ 有没有会使用zlib库解压zip包的
bool unzip(const char *DestName, const char *SrcName)
{
//解压缩文件时的源buffer
char* uSorceBuffer = new char[1024*1024*2];
memset(uSorceBuffer,0,sizeof(char)*1024*1024*2);
FILE* fp3; //打开欲解压文件的文件指针
FILE* fp4; //创建解压文件的文件指针
errno_t err; //错误变量的定义
//打开欲解压的文件
err = fopen_s(&fp3, SrcName, "rb");
if (err)
{
printf("文件打开失败! \n");
return false;
}
//获取欲解压文件的大小
long ucur = ftell(fp3);
fseek(fp3, 0L, SEEK_END);
long ufileLength = ftell(fp3);
fseek(fp3, ucur, SEEK_SET);
//读取文件到buffer
int count = fread(uSorceBuffer, 1, ufileLength, fp3);
fclose(fp3);
uLongf uDestBufferLen = 1024*1024*11;//此处长度需要足够大以容纳解压缩后数据
char* uDestBuffer = (char*)::calloc((uInt)uDestBufferLen, 1);
//解压缩buffer中的数据
err = uncompress((Bytef*)uDestBuffer, (uLongf*)&uDestBufferLen, (Bytef*)uSorceBuffer, (uLongf)ufileLength);
if (err != Z_OK)
{
return false;
}
//创建一个文件用来写入解压缩后的数据
err = fopen_s(&fp4, DestName, "wb");
if (err)
{
printf("解压缩文件创建失败! \n");
return false;
}
//写入数据
fwrite(uDestBuffer, uDestBufferLen, 1, fp4);
fclose(fp4);
return true;
⑺ python怎样压缩和解压缩ZIP文件
在1.6版中,Python 就已经提供了 zipfile 模块可以进行这样的操作。不过 Python 中的 zipfile 模块不能处理多卷的情况,不过这种情况并不多见,因此在通常情况下已经足够使用了。
zipfile 模块可以让你打开或写入一个 zip 文件。比如:
import zipfile
z = zipfile.ZipFile('zipfilename', mode='r')
这样就打开了一个 zip 文件,如果mode为'w'或'a'则表示要写入一个 zip 文件。如果是写入,则还可以跟上第三个参数:
compression=zipfile.ZIP_DEFLATED 或
compression=zipfile.ZIP_STORED ZIP_DEFLATED是压缩标志,如果使用它需要编译了zlib模块。而后一个只是用zip进行打包,并不压缩。
在打开了zip文件之后就可以根据需要是读出zip文件的内容还是将内容保存到 zip 文件中。
读出zip中的内容
很简单,zipfile 对象提供了一个read(name)的方法。name为 zip文件中的一个文件入口,执行完成之后,将返回读出的内容,你把它保存到想到的文件中即可。
写入zip文件
有两种方式,一种是直接写入一个已经存在的文件,另一种是写入一个字符串。
对 于第一种使用 zipfile 对象的 write(filename, arcname, compress_type),后两个参数是可以忽略的。第一个参数是文件名,第二个参数是表示在 zip 文件中的名字,如果没有给出,表示使用与filename一样的名字。compress_type是压缩标志,它可以覆盖创建 zipfile 时的参数。第二种是使用 zipfile 对象的 writestr(zinfo_or_arcname, bytes),第一个参数是zipinfo 对象或写到压缩文件中的压缩名,第二个参数是字符串。使用这个方法可以动态的组织文件的内容。
需要注意的是在读出时,因为只能读出内容,因此如果想实现按目录结构展开 zip 文件的话,这些操作需要自已来完成,比如创建目录,创建文件并写入。而写入时,则可以根据需要动态组织在 zip 文件中的目录结构,这样可以不按照原来的目录结构来生成 zip 文件。
于是我为了方便使用,创建了自已的一个 ZFile 类,主要是实现象 winrar 的右键菜单中的压缩到的功能--即将一个zip文件压缩到指定目录,自动创建相应的子目录。再有就是方便生成 zip 文件。类源码为:
# coding:cp936
# Zfile.py
# xxteach.com
import zipfile
import os.path
import os
class ZFile(object):
def __init__(self, filename, mode='r', basedir=''):
self.filename = filename
self.mode = mode
if self.mode in ('w', 'a'):
self.zfile = zipfile.ZipFile(filename, self.mode, compression=zipfile.ZIP_DEFLATED)
else:
self.zfile = zipfile.ZipFile(filename, self.mode)
self.basedir = basedir
if not self.basedir:
self.basedir = os.path.dirname(filename)
def addfile(self, path, arcname=None):
path = path.replace('//', '/')
if not arcname:
if path.startswith(self.basedir):
arcname = path[len(self.basedir):]
else:
arcname = ''
self.zfile.write(path, arcname)
def addfiles(self, paths):
for path in paths:
if isinstance(path, tuple):
self.addfile(*path)
else:
self.addfile(path)
def close(self):
self.zfile.close()
def extract_to(self, path):
for p in self.zfile.namelist():
self.extract(p, path)
def extract(self, filename, path):
if not filename.endswith('/'):
f = os.path.join(path, filename)
dir = os.path.dirname(f)
if not os.path.exists(dir):
os.makedirs(dir)
file(f, 'wb').write(self.zfile.read(filename))
def create(zfile, files):
z = ZFile(zfile, 'w')
z.addfiles(files)
z.close()
def extract(zfile, path):
z = ZFile(zfile)
z.extract_to(path)
z.close()
⑻ python怎样压缩和解压缩ZIP文件
1、python使用zipfile模块压缩和解压ZIP文件
2、读取zip文件
首先,通过zipfile模块打开指定zip文件,如:
zpfd = zipfile.ZipFile(path, mode='r')
对于zipfile,其标志与open所用的打开文件标志有所不同,不能识别 'rb'。
然后,读取zip文件中的内容,zipfile对象提供一个read(name)的方法,name为zip文件中的一个文件入口,执行完成之后,将返回读出的内容,如:
for filename in zpfd.namelist():
tmpcont = zpfd.read(filename)
print 'len(tmpcont)', 'tmpcont'
需要注意的是,读取zip文件时,只能读取内容
3、写入zip文件
首先,需要zipfile模块写打开或创建zip文件,如:
zpfd = zipfile.ZipFile(path, mode='w')
写打开是标志可以为'w'或'a'('a'表示写入一个zip文件), 或者传入第三个参数cmopression压缩标志
compression=zipfile.ZIP_DEFLATED 需要导入zlib模块
compression=zipfile.ZIP_STORED则表示只对文件进行打包,并不压缩
写
入有两种方式,一种是直接写入一个已经存在的文件,可使用zipfile对象中write(filename, arcname,
compress_type)第一个参数为文件名,第二个参数指写入zip文件中的文件名,默认与filename一致,第三个参数压缩标志可以覆盖打开
zipfile时的使用参数;另一种是写入一个字符串,可使用zipfile对象中的writestr(zinfo_or_arcname,
bytes),第一个参数是zipinfo对象或写到zip文件中的压缩名,第二个参数是待写入的字符串
4、最后,对于打开的zipfile对象需要进行关闭,从而使得写入内容真正写入磁盘,即:
zpfd.close()
⑼ python怎样压缩和解压缩ZIP文件
1、说明
python使用zipfile模块来压缩和解压zip文件
2、代码
importos,os.path
importzipfile
defzip_dir(dirname,zipfilename):
filelist=[]
ifos.path.isfile(dirname):
filelist.append(dirname)
else:
forroot,dirs,filesinos.walk(dirname):
fornameinfiles:
filelist.append(os.path.join(root,name))
zf=zipfile.ZipFile(zipfilename,"w",zipfile.zlib.DEFLATED)
fortarinfilelist:
arcname=tar[len(dirname):]
#printarcname
zf.write(tar,arcname)
zf.close()
defunzip_file(zipfilename,unziptodir):
ifnotos.path.exists(unziptodir):os.mkdir(unziptodir)
zfobj=zipfile.ZipFile(zipfilename)
fornameinzfobj.namelist():
name=name.replace('\','/')
ifname.endswith('/'):
os.mkdir(os.path.join(unziptodir,name))
else:
ext_filename=os.path.join(unziptodir,name)
ext_dir=os.path.dirname(ext_filename)
ifnotos.path.exists(ext_dir):os.mkdir(ext_dir)
outfile=open(ext_filename,'wb')
outfile.write(zfobj.read(name))
outfile.close()
if__name__=='__main__':
zip_dir(r'd:/python/test',r'd:/python/test.zip')
unzip_file(r'd:/python/test.zip',r'd:/python/test2')
执行结果
顺利生成相应文件
3、备注
zip文件格式是通用的文档压缩标准,在zipfile模块中,使用ZipFile类来操作zip文件,下面具体介绍一下:
class zipfile.ZipFile(file[, mode[, compression[, allowZip64]]])
创建一个ZipFile对象,表示一个zip文件。参数file表示文件的路径或类文件对象(file-like object);参数mode指示打开zip文件的模式,默认值为'r',表示读已经存在的zip文件,也可以为'w'或'a','w'表示新建一个zip文档或覆盖一个已经存在的zip文档,'a'表示将数据附加到一个现存的zip文档中。参数compression表示在写zip文档时使用的压缩方法,它的值可以是zipfile. ZIP_STORED 或zipfile. ZIP_DEFLATED。如果要操作的zip文件大小超过2G,应该将allowZip64设置为True。
ZipFile还提供了如下常用的方法和属性:
ZipFile.getinfo(name):
获取zip文档内指定文件的信息。返回一个zipfile.ZipInfo对象,它包括文件的详细信息。将在下面 具体介绍该对象。
ZipFile.infolist()
获取zip文档内所有文件的信息,返回一个zipfile.ZipInfo的列表。
ZipFile.namelist()
获取zip文档内所有文件的名称列表。
ZipFile.extract(member[, path[, pwd]])
⑽ python怎样压缩和解压缩ZIP文件
1、python使用zipfile模块压缩和解压ZIP文件
2、读取zip文件
首先,通过zipfile模块打开指定zip文件,如:
zpfd = zipfile.ZipFile(path, mode='r')
对于zipfile,其标志与open所用的打开文件标志有所不同,不能识别 'rb'。
然后,读取zip文件中的内容,zipfile对象提供一个read(name)的方法,name为zip文件中的一个文件入口,执行完成之后,将返回读出的内容,如:
for filename in zpfd.namelist():
tmpcont = zpfd.read(filename)
print 'len(tmpcont)', 'tmpcont'
需要注意的是,读取zip文件时,只能读取内容
3、写入zip文件
首先,需要zipfile模块写打开或创建zip文件,如:
zpfd = zipfile.ZipFile(path, mode='w')
写打开是标志可以为'w'或'a'('a'表示写入一个zip文件), 或者传入第三个参数cmopression压缩标志
compression=zipfile.ZIP_DEFLATED 需要导入zlib模块
compression=zipfile.ZIP_STORED则表示只对文件进行打包,并不压缩
写入有两种方式,一种是直接写入一个已经存在的文件,可使用zipfile对象中write(filename, arcname, compress_type)第一个参数为文件名,第二个参数指写入zip文件中的文件名,默认与filename一致,第三个参数压缩标志可以覆盖打开zipfile时的使用参数;另一种是写入一个字符串,可使用zipfile对象中的writestr(zinfo_or_arcname, bytes),第一个参数是zipinfo对象或写到zip文件中的压缩名,第二个参数是待写入的字符串
4、最后,对于打开的zipfile对象需要进行关闭,从而使得写入内容真正写入磁盘,即:
zpfd.close()