来源: http://blog.csdn.net/turingo/article/details/8178510#comments
不少网友读完zlib库compress和uncompress函数的使用方法这篇文章之后,仍然无法独立完成简单的文件压缩和解压缩功能,为此作者在这里追加这样的演示代码。问题的根源在于这些网友对于字符串和字节流的概念非常的模糊,对文本文件和二进制文件的区别常常模棱两可,其实字节流可以表示所有的数据,二进制文件才是任何文件的本质。字节流是一个字节接一个字节,并没有结束符号,所以需要给它一个长度信息。二进制文件是一个字节接一个字节,并没有换行符之类的。
文件压缩的时候,可以通过源文件的长度自动计算缓冲区的长度,压缩后写入目标文件之前,需先保留源文件和目标数据的长度作为解压缩的依据,参考如下代码:
-
#include
-
#include
-
#include
-
-
int main(int argc, char* argv[])
-
{
-
FILE* file;
-
uLong flen;
-
unsigned char* fbuf = NULL;
-
uLong clen;
-
unsigned char* cbuf = NULL;
-
-
-
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;
-
}
文件解压缩的时候,可以通过保留信息得到缓冲区和数据流的大小,这样解压缩后直接保存即可,参考如下代码:
-
#include
-
#include
-
#include
-
-
int main(int argc, char* argv[])
-
{
-
FILE* file;
-
uLong flen;
-
unsigned char* fbuf = NULL;
-
uLong ulen;
-
unsigned char* ubuf = NULL;
-
-
-
if(argc < 3)
-
{
-
printf("Usage: zudemo srcfile dstfile\n");
-
return -1;
-
}
-
-
if((file = fopen(argv[1], "rb")) == NULL)
-
{
-
printf("Can\'t open %s!\n", argv[1]);
-
return -1;
-
}
-
-
fread(&ulen, sizeof(uLong), 1, file);
-
fread(&flen, sizeof(uLong), 1, file);
-
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);
-
-
if((ubuf = (unsigned char*)malloc(sizeof(unsigned char) * ulen)) == NULL)
-
{
-
printf("No enough memory!\n");
-
fclose(file);
-
return -1;
-
}
-
if(uncompress(ubuf, &ulen, fbuf, flen) != Z_OK)
-
{
-
printf("Uncompress %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(ubuf, sizeof(unsigned char), ulen, file);
-
fclose(file);
-
-
free(fbuf);
-
free(ubuf);
-
-
return 0;
-
}
-
阅读(5036) | 评论(0) | 转发(0) |