pistacchio
pistacchio

Reputation: 58963

C: Zlib compress not working

I'm trying a very simple thing: read a minimal text file and compress it with the compress() utility from zlib. I think I've done everything fine, I allocate filesize * 10 for the output, it should be more that enough, but I keep getting -5 (Z_BUF_ERROR) as result of the operation. Any help?

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

Upvotes: 1

Views: 653

Answers (2)

Giorgi Moniava
Giorgi Moniava

Reputation: 28685

Try

uLongf compressed_data_size = compressBound(input_size);

compressBound should be available in zlib.

Also you are better of probably using rb in fopen like I mentioned in my comment before.

Upvotes: 1

Mark Adler
Mark Adler

Reputation: 112627

Use fopen(filename, "rb"). If you are on Windows that b is important to avoid corruption of binary data.

Use compressBound() in zlib instead of input_size * 10 and set compressed_data_size before calling compress(). (You do not need to and should not write your own compressBound().)

Upvotes: 2

Related Questions