我正在尝试使用compress()
和uncompress()
函数压缩和解压缩随机生成的字符串与zlib的最简单方式。但是在执行uncompress()
函数后,我得到Z_DATA_ERROR (-3)
。有人知道我的错误在哪里吗?
以下是代码:
int
main(int argc __attribute ((unused)),char **argv __attribute ((unused)))
{
unsigned char* cara_in;
unsigned char* cara_inter;
unsigned char* cara_out;
size_t i;
size_t len = 1024*50; //50 KBytes
int ret;
cara_in = (unsigned char*)malloc(sizeof(unsigned char*)*len);
cara_inter = (unsigned char*)malloc(sizeof(unsigned char*)*len);
cara_out = (unsigned char*)malloc(sizeof(unsigned char*)*len);
uLongf size_cara_inter;
uLongf size_cara_out;
srand(time (NULL));
/* Generating */
for(i=0; i < len-1;i++)
{
cara_in[i] = (int)(rand() %24 +65);
}
size_cara_inter = 2*len;
ret = compress(
cara_inter,
&size_cara_inter,
cara_in,
(uLongf)strlen((const char*)cara_in)
);
if(ret != Z_OK)
{
/* error */
return EXIT_FAILURE;
}
size_cara_out = 2*len;
ret = uncompress(
cara_out,
&size_cara_out,
cara_inter,
(uLongf)strlen((const char*)cara_inter)
);
if(ret != Z_OK)
{
/* error */
return EXIT_FAILURE;
}
/* compare */
ret = strcmp((const char*)cara_in, (const char*)cara_out);
if(ret != 0){
/*problem*/
fprintf(stderr, "\nOuups! :(\nResult of cmp is %d", ret);
fflush(stderr);
fprintf(
stderr,
"\ncara_in length : %d, cara_out length : %d\n",
(unsigned)strlen((const char*)cara_in), (unsigned)strlen((const char*)cara_out)
);
fflush(stderr);
}
return EXIT_SUCCESS;
}
答案 0 :(得分:0)
这是纠正后的源代码,感谢弗朗西斯:
int
main(int argc __attribute ((unused)),char **argv __attribute ((unused)))
{
unsigned char* cara_in;
unsigned char* cara_inter;
unsigned char* cara_out;
size_t i;
size_t len = 1024*50; //50 KBytes
int ret;
cara_in = (unsigned char*)malloc(sizeof(unsigned char*)*len);
cara_inter = (unsigned char*)malloc(sizeof(unsigned char*)*len);
cara_out = (unsigned char*)malloc(sizeof(unsigned char*)*len);
uLongf size_cara_inter;
uLongf size_cara_out;
srand(time (NULL));
/* Generating */
for(i=0; i < len-1;i++)
{
cara_in[i] = (int)(rand() %24 +65);
}
cara_in[len] = '\0';
size_cara_inter = 2*len;
ret = compress(
cara_inter,
&size_cara_inter,
cara_in,
(uLongf)strlen((const char*)cara_in)
);
if(ret != Z_OK)
{
/* error */
return EXIT_FAILURE;
}
size_cara_out = 2*len;
ret = uncompress(
cara_out,
&size_cara_out,
cara_inter,
size_cara_inter
);
if(ret != Z_OK)
{
/* error */
return EXIT_FAILURE;
}
/* compare */
ret = strcmp((const char*)cara_in, (const char*)cara_out);
if(ret != 0){
/*problem*/
fprintf(stderr, "\nOuups! :(\nResult of cmp is %d", ret);
fflush(stderr);
fprintf(
stderr,
"\ncara_in length : %d, cara_out length : %d\n",
(unsigned)strlen((const char*)cara_in), (unsigned)strlen((const char*)cara_out)
);
fflush(stderr);
}
return EXIT_SUCCESS;
}