Thursday, January 5, 2012

[ANSI C] How to unpack .GZ archive with ZLIB library

Introduction

This ANSI C code uses ZLIB library to unpack .GZ archives.

It also extracts information from .GZ file header.

Source code

https://github.com/vurdalakov/codeblog_examples/tree/master/ansi_c/gzunpack

Usage

#include "gzunpack.h"

...

    // read .GZ file header

    FILE *packedFileHandle = fopen("test1.gz", "rb");

    GzFileHeader *gzFileHeader = gzUnpackHeader(packedFileHandle);

    printf("Header:\n");
    printf("compressionMethod = %d\n", gzFileHeader->compressionMethod);
    printf("originalFileName = '%s'\n", gzFileHeader->originalFileName);
    printf("fileComment = '%s'\n", gzFileHeader->fileComment);

    // unpack .GZ file

    fseek(packedFileHandle, 0, SEEK_SET); // rewind

    FILE *unpackedFileHandle = fopen(gzFileHeader->originalFileName, "wb");

    gzUnpackFile(packedFileHandle, unpackedFileHandle);

    // free resources

    fclose(unpackedFileHandle);
    fclose(packedFileHandle);

    gzFreeHeader(gzFileHeader);

Links

No comments:

Post a Comment