gpt4 book ai didi

c - zlib 压缩和解压使用

转载 作者:太空宇宙 更新时间:2023-11-04 04:25:53 25 4
gpt4 key购买 nike

我正在尝试使用 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;
}

最佳答案

这里是更正后的源代码,感谢 Francis:

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;
}

关于c - zlib 压缩和解压使用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41618069/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com