C:Zlib压缩不起作用

时间:2015-08-04 09:06:38

标签: c zlib

我正在尝试一个非常简单的事情:读取一个最小的文本文件并使用zlib中的compress()实用程序对其进行压缩。我想我已经完成了一切,我为输出分配了文件大小* 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;
}

2 个答案:

答案 0 :(得分:2)

使用fopen(filename, "rb")。如果您在Windows上b对于避免二进制数据损坏非常重要。

在zlib而不是input_size * 10中使用compressBound()并在调用compressed_data_size之前设置compress()。 (您不需要也不应该编写自己的compressBound()。)

答案 1 :(得分:1)

尝试

uLongf compressed_data_size = compressBound(input_size);

compressBound应该在zlib中提供。

另外,您最好使用rb中的fopen,就像我之前在评论中提到的那样。