Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using zlib with C

Tags:

c

zlib

I am currently learning C, and am having some issues with trying to make a small program that utilizes zlib.

I have managed to compile my application (using Codeblocks/MinGW) with the zlib libraries, and compilation works fine. I have used an example based upon the zpipe.c example found over at the official zlib site (zlib.net).

On execution, the output zip file is created, but it seems malformed and/or empty. I am unable to open it using 7zip.

Here is the code that I have modified. I have simply replaced the main() function within zpipe.c.

int main() {
    printf("Compression test...");

    int ret;
    FILE *fpsource;
    FILE *fpdest;

    fpsource = fopen("test.txt", "rb");
    fpdest = fopen("output.zip", "wb");

    ret = def(fpsource, fpdest, Z_DEFAULT_COMPRESSION);
    if (ret != Z_OK) {
        printf("failure\n");
        zerr(ret);
    }
    else {
        printf("success..\n");
    }

    fclose(fpsource);
    fclose(fpdest);

    return EXIT_SUCCESS;
}

I receive no errors, and my 'success' message is printed. It's just the output file is corrupt.

like image 856
Ricky Hewitt Avatar asked Aug 06 '26 11:08

Ricky Hewitt


1 Answers

zpipe.c as-is will generate the zlib format, which is raw deflate data wrapped in a zlib header and trailer. 7zip won't recognize that. It will recognize the gzip or zip format, which are entirely different wrappers on the same raw deflate data.

You can modify zpipe.c to use deflateInit2 (and inflateInit2) instead of the versions without the "2" to select the gzip format instead of the zlib format. You can read zlib.h for how to do this.

like image 56
Mark Adler Avatar answered Aug 08 '26 01:08

Mark Adler



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!