follow my heart...
分类: C/C++
2006-06-06 15:48:54
//用zlib实现压缩与解压缩
//在winxpsp2+devc++4.9.9.2实现
//链接参数中加入-lz
//将zlib1.dll加入程序目录
//kzip功能是压缩文件,kunzip是解压缩文件
//仅限于对单个文件的压缩与解压缩
#i nclude
#i nclude
#i nclude
#i nclude
using namespace std;
void kzip(char *inFile,char *outFile)
{
FILE *FileIn=fopen(inFile,"rb");
FILE *FileOut=fopen(outFile,"wb");
fseek(FileIn,0,SEEK_END);
unsigned long FileInSize=ftell(FileIn);
void *RawDataBuff=malloc(FileInSize);
void *CompDataBuff=NULL;
uLongf CompBuffSize=(uLongf)(FileInSize+(FileInSize*0.1)+12);
CompDataBuff=malloc((size_t)(CompBuffSize));
fseek(FileIn,0,SEEK_SET);
fread(RawDataBuff,FileInSize,1,FileIn);
uLongf DestBuffSize;
compress2((Bytef*)CompDataBuff,(uLongf*)&DestBuffSize,(const Bytef*)RawDataBuff,(uLongf)FileInSize,Z_BEST_COMPRESSION);
fwrite(CompDataBuff,DestBuffSize,1,FileOut);
}
void kunzip(char *inFile,char *outFile)
{
//the input file, this is the output file from part one
FILE *FileIn = fopen(inFile, "rb");
//output file
FILE *FileOut = fopen(outFile, "wb");
//get the file size of the input file
fseek(FileIn, 0, SEEK_END);
unsigned long FileInSize = ftell(FileIn);
//buffers for the raw and uncompressed data
void *RawDataBuff = malloc(FileInSize);
void *UnCompDataBuff = NULL;
//read in the contents of the file into the source buffer
fseek(FileIn, 0, SEEK_SET);
fread(RawDataBuff, FileInSize, 1, FileIn);
//allocate a buffer big enough to hold the uncompressed data, we can cheat here
//because we know the file size of the original
uLongf UnCompSize = 482000;
UnCompDataBuff = malloc(UnCompSize);
//all data we require is ready so compress it into the source buffer, the exact
//size will be stored in UnCompSize
uncompress((Bytef*)UnCompDataBuff, &UnCompSize, (const Bytef*)RawDataBuff, FileInSize);
//write the decompressed data to disk
fwrite(UnCompDataBuff, UnCompSize, 1, FileOut);
}
int main(int argc, char *argv[])
{
printf("1、压缩\n2、解压缩\n");
int n=getchar();
if (n==1)
{
kzip("in.jpeg","out.dat");
}
else
{
kunzip("Out.dat","in.jpeg");
}
system("PAUSE");
return EXIT_SUCCESS;
}