amplifier
amplifier

Reputation: 1833

ZLib creates a damaged archive

I use zlib 1.211 as a dynamic library and VS2019.

I create a simple zip from a txt file

FILE* input = fopen("D:\\1.txt", "rb");
FILE* output = fopen("D:\\1.zip", "wb");
/* do compression if no arguments */
bool ok = compress_file(input, output);

fclose(output);
fclose(input);

Compression function is:

bool compress_file(FILE* src, FILE* dst)
{
    uint8_t inbuff[CHUNK_SIZE];
    uint8_t outbuff[CHUNK_SIZE];
    z_stream stream = { 0 };

    if (deflateInit(&stream, COMPRESSION_LEVEL) != Z_OK)
    {
        fprintf(stderr, "deflateInit(...) failed!\n");
        return false;
    }

    int flush;
    do {
        stream.avail_in = fread(inbuff, 1, CHUNK_SIZE, src);
        if (ferror(src))
        {
            fprintf(stderr, "fread(...) failed!\n");
            deflateEnd(&stream);
            return false;
        }

        flush = feof(src) ? Z_FINISH : Z_NO_FLUSH;
        stream.next_in = inbuff;

        do {
            stream.avail_out = CHUNK_SIZE;
            stream.next_out = outbuff;
            deflate(&stream, flush);
            uint32_t nbytes = CHUNK_SIZE - stream.avail_out;

            if (fwrite(outbuff, 1, nbytes, dst) != nbytes ||
                ferror(dst))
            {
                fprintf(stderr, "fwrite(...) failed!\n");
                deflateEnd(&stream);
                return false;
            }
        } while (stream.avail_out == 0);
    } while (flush != Z_FINISH);

    deflateEnd(&stream);
    return true;
}

But when I try to open the created zip by, for example, TotalCommander or WinRAR I get "Error in package file".

Upvotes: 0

Views: 109

Answers (1)

Mark Adler
Mark Adler

Reputation: 112219

zlib doesn't make zip archives. Your code makes zlib streams. Two different things.

Upvotes: 2

Related Questions