(root)/
gzip-1.13/
sample/
zread.c
       1  #include <config.h>
       2  #include <stdio.h>
       3  #include <stdlib.h>
       4  
       5  /* Trivial example of reading a gzip'ed file or gzip'ed standard input
       6   * using stdio functions fread(), getc(), etc... fseek() is not supported.
       7   * Modify according to your needs. You can easily construct the symmetric
       8   * zwrite program.
       9   *
      10   * Usage: zread [file[.gz]]
      11   * This programs assumes that gzip is somewhere in your path.
      12   */
      13  int
      14  main (int argc, char **argv)
      15  {
      16      FILE *infile;
      17      char cmd[256];
      18      char buf[BUFSIZ];
      19      int n;
      20  
      21      if (argc < 1 || argc > 2) {
      22          fprintf(stderr, "usage: %s [file[.gz]]\n", argv[0]);
      23          exit(EXIT_FAILURE);
      24      }
      25      strcpy(cmd, "gzip -dc ");  /* use "gzip -c" for zwrite */
      26      if (argc == 2) {
      27          strncat(cmd, argv[1], sizeof(cmd)-strlen(cmd));
      28      }
      29      infile = popen(cmd, "r");  /* use "w" for zwrite */
      30      if (infile == NULL) {
      31          fprintf(stderr, "%s: popen('%s', 'r') failed\n", argv[0], cmd);
      32          exit(EXIT_FAILURE);
      33      }
      34      /* Read one byte using getc: */
      35      n = getc(infile);
      36      if (n == EOF) {
      37          pclose(infile);
      38          exit(EXIT_SUCCESS);
      39      }
      40      putchar(n);
      41  
      42      /* Read the rest using fread: */
      43      for (;;) {
      44          n = fread(buf, 1, BUFSIZ, infile);
      45          if (n <= 0) break;
      46          fwrite(buf, 1, n, stdout);
      47      }
      48      if (pclose(infile) != 0) {
      49          fprintf(stderr, "%s: pclose failed\n", argv[0]);
      50          exit(EXIT_FAILURE);
      51      }
      52      exit(EXIT_SUCCESS);
      53      return 0; /* just to make compiler happy */
      54  }