zlib

zlib

CategoryData compression
Licensezlib License
Websitehttps://zlib.net/

zlib is a software Library used for data compression. It uses Deflate algorithm, one of lossless data compression.

Sample code on C

#include <stdio.h>
#include <zlib.h>

enum {
  BUF_SIZE = 1024,
};

typedef enum ProcType {
  INFLATE,
  DEFLATE,
} ProcType;

void proc(FILE *fin, FILE *fout, ProcType type)
{
  char in[BUF_SIZE];
  char out[BUF_SIZE];
  z_stream z = {0};

  if (type == DEFLATE) {
    deflateInit(&z, Z_DEFAULT_COMPRESSION);
  } else {
    inflateInit(&z);
  }

  z.next_out = out;
  z.avail_out = BUF_SIZE;

  for (;;) {
    int ret, flag = Z_NO_FLUSH;
    if (z.avail_in == 0) {  /* next input */
      z.next_in = in;
      z.avail_in = fread(in, 1, BUF_SIZE, fin);
      /* last input */
      if (z.avail_in < BUF_SIZE) {
        flag = Z_FINISH;
      }
    }
    if (type == DEFLATE) {
      ret = deflate(&z, flag);
    } else {
      ret = inflate(&z, Z_NO_FLUSH);
    }
    if (z.avail_out == 0 || ret == Z_STREAM_END) {
      fwrite(out, 1, BUF_SIZE - z.avail_out, fout);
      if (ret == Z_STREAM_END) {
        break;
      }
      z.next_out = out;
      z.avail_out = BUF_SIZE;
    }
  }
  printf("total input  : %dbytes\n", (int)z.total_in);
  printf("total output : %dbytes\n", (int)z.total_out);
  if (type == DEFLATE) {
    deflateEnd(&z);
  } else {
    inflateEnd(&z);
  }
}

int main(int argc, char **argv)
{
  FILE *fin = NULL, *fout = NULL;

  if (argc != 4) {
    fprintf(stderr, "usage : ztest [c|d] from-file to-file\n");
    fprintf(stderr, "c : compress\n");
    fprintf(stderr, "d : decompress\n");
    goto FINISH;
  }

  fin = fopen(argv[2], "rb");
  if (fin == NULL) {
    fprintf(stderr, "cannot open file '%s'\n", argv[2]);
    goto FINISH;
  }
  fout = fopen(argv[3], "wb");
  if (fout == NULL) {
    fprintf(stderr, "cannot open file '%s'\n", argv[3]);
    goto FINISH;
  }

  switch (argv[1][0]) {
  case 'c':
    proc(fin, fout, DEFLATE);
    break;
  case 'd':
    proc(fin, fout, INFLATE);
    break;
  default:
    fprintf(stderr, "unknown option '%s'\n", argv[1]);
    break;
  }

FINISH:
  if (fin) {
    fclose(fin);
  }
  if (fout) {
    fclose(fout);
  }

  return 0;
}

External link