Read a compressed file with gzFile, gzopen, and gzread in C

This is an example C program illustrating the use of the gzFile structure to read a file. This program looks for an input file of the form "text.gz" to read in. Note that if the file is not in the gzip format, gzopen and gzread will not produce an error but just read it without doing any uncompressing.

#include <stdio.h>
#include <stdlib.h>
#include <zlib.h>
#include <errno.h>
#include <string.h>

/* The name of the test file to read. */

static const char * file_name = "text.gz";

/* Size of the block of memory to use for reading. */

#define LENGTH 0x1000

int main ()
    gzFile file;
    file = gzopen (file_name, "r");
    if (! file) {
        fprintf (stderr, "gzopen of '%s' failed: %s.\n", file_name,
                 strerror (errno));
            exit (EXIT_FAILURE);
    while (1) {
        int err;                    
        int bytes_read;
        unsigned char buffer[LENGTH];
        bytes_read = gzread (file, buffer, LENGTH - 1);
        buffer[bytes_read] = '\0';
        printf ("%s", buffer);
        if (bytes_read < LENGTH - 1) {
            if (gzeof (file)) {
            else {
                const char * error_string;
                error_string = gzerror (file, & err);
                if (err) {
                    fprintf (stderr, "Error: %s.\n", error_string);
                    exit (EXIT_FAILURE);
    gzclose (file);
    return 0;


Copyright © Ben Bullock 2009-2023. All rights reserved. For comments, questions, and corrections, please email Ben Bullock ( or use the discussion group at Google Groups. / Privacy / Disclaimer