用zlib压缩解压缩,请各位看看程序有什么问题
关于zlib压缩解压缩问题,请各位看看程序哪有问题?
1)createfile.c 将3句话压缩存入file.txt文档中
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "zlib.h"
unsigned char* compression(const char* s)
{
unsigned char *buf;
unsigned long slen = strlen(s) +1;
unsigned long buflen = compressBound(slen);
buf = (unsigned char*)malloc(sizeof(unsigned char)*buflen);
compress(buf, &buflen, (const Bytef *)s, slen);
return buf;
}
void main()
{
FILE *pf;
char *p1 = "this document is distributed in the hope that it will be useful, but without any warranty;";
char *p2 = "without even the implied warranty of merchantability or fittness for a particular purpose;";
char *p3 = "you should have received a copy of the GNU General Public License along with this document;";
pf = fopen("file.txt", "wr");
unsigned char* temp;
temp = compression(p1);
fprintf(pf, "%s\n", temp);
free(temp); //相当用free了compression函数中的buf?
temp = compression(p2);
fprintf(pf, "%s\n", temp);
free(temp);
temp = compression(p3);
fprintf(pf, "%s\n", temp);
free(temp);
}
2) 从file.txt文档中读取压缩字符串进行解压缩,将解压后的字符串存入newfile.txt中
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#include"zlib.h"
#define LINE 1024
unsigned char *decompression(char* s)
{
unsigned char *dest;
unsigned long len = strlen(s) + 1;
unsigned long destlen = (len<<1)*2;
dest = (unsigned char*)malloc(sizeof(unsigned char)*destlen);
uncompress(dest, &destlen, s, len);
return dest;
}
void main()
{
FILE *pf = fopen("file.txt", "r");
FILE *nf = fopen("newfile.txt", "wr");
unsigned char *buf = (unsigned char *)malloc(sizeof(unsigned char)*LINE);
char *p;
if (pf == NULL)
{
printf ("File open error!\n");
exit (0);
}
p = fgets(buf, LINE, pf);
while (p)
{
unsigned char *temp = decompression(buf);
fprintf(nf, "%s", temp);
free(temp);
free(buf);
buf = (char *)malloc(sizeof(char)*LINE);
p = fgets(buf, LINE, pf);
}
free(buf);
fclose(pf);
fclose(nf);
}
若1)中输入的3句话均以大写开头,则能顺利解压成原文,若为小写则后2句无法解压。个人觉得是我的解压函数有问题,望解答!
非常感谢!