C: Zlib 压缩不工作
C: Zlib compress not working
我正在尝试一个非常简单的事情:读取一个最小文本文件并使用 zlib 中的 compress()
实用程序对其进行压缩。我想我做的一切都很好,我为输出分配了 filesize * 10,它应该足够了,但是作为操作的结果我一直得到 -5 (Z_BUF_ERROR)。
有帮助吗?
#include <stdio.h>
#include <stdlib.h>
#include "zlib.h"
#define FILE_TO_OPEN "text.txt"
static char* readcontent(const char *filename, int* size)
{
char* fcontent = NULL;
int fsize = 0;
FILE* fp = fopen(filename, "r");
if(fp) {
fseek(fp, 0, SEEK_END);
fsize = ftell(fp);
rewind(fp);
fcontent = (char*) malloc(sizeof(char) * fsize);
fread(fcontent, 1, fsize, fp);
fclose(fp);
}
*size = fsize;
return fcontent;
}
int main(int argc, char const *argv[])
{
int input_size;
char* content_of_file = readcontent(FILE_TO_OPEN, &input_size);
printf("%d\n", input_size);
uLongf compressed_data_size;
char* compressed_data = malloc(sizeof(char) * (input_size * 10));
int result = compress((Bytef*) compressed_data, (uLongf*)&compressed_data_size, (const Bytef*)content_of_file, (uLongf)input_size);
printf("%d\n", result);
return 0;
}
尝试
uLongf compressed_data_size = compressBound(input_size);
compressBound
应该在 zlib
中可用。
此外,您最好在 fopen
中使用 rb
,就像我之前在评论中提到的那样。
使用fopen(filename, "rb")
。如果您在 Windows 上,那么 b
对于避免二进制数据损坏很重要。
在 zlib 中使用 compressBound()
而不是 input_size * 10
并在调用 compress()
之前设置 compressed_data_size
。 (你不需要也不应该自己写 compressBound()
。)
我正在尝试一个非常简单的事情:读取一个最小文本文件并使用 zlib 中的 compress()
实用程序对其进行压缩。我想我做的一切都很好,我为输出分配了 filesize * 10,它应该足够了,但是作为操作的结果我一直得到 -5 (Z_BUF_ERROR)。
有帮助吗?
#include <stdio.h>
#include <stdlib.h>
#include "zlib.h"
#define FILE_TO_OPEN "text.txt"
static char* readcontent(const char *filename, int* size)
{
char* fcontent = NULL;
int fsize = 0;
FILE* fp = fopen(filename, "r");
if(fp) {
fseek(fp, 0, SEEK_END);
fsize = ftell(fp);
rewind(fp);
fcontent = (char*) malloc(sizeof(char) * fsize);
fread(fcontent, 1, fsize, fp);
fclose(fp);
}
*size = fsize;
return fcontent;
}
int main(int argc, char const *argv[])
{
int input_size;
char* content_of_file = readcontent(FILE_TO_OPEN, &input_size);
printf("%d\n", input_size);
uLongf compressed_data_size;
char* compressed_data = malloc(sizeof(char) * (input_size * 10));
int result = compress((Bytef*) compressed_data, (uLongf*)&compressed_data_size, (const Bytef*)content_of_file, (uLongf)input_size);
printf("%d\n", result);
return 0;
}
尝试
uLongf compressed_data_size = compressBound(input_size);
compressBound
应该在 zlib
中可用。
此外,您最好在 fopen
中使用 rb
,就像我之前在评论中提到的那样。
使用fopen(filename, "rb")
。如果您在 Windows 上,那么 b
对于避免二进制数据损坏很重要。
在 zlib 中使用 compressBound()
而不是 input_size * 10
并在调用 compress()
之前设置 compressed_data_size
。 (你不需要也不应该自己写 compressBound()
。)