version 1.3.13
[gzip.git] / sample / zread.c
blob12c5a357106904450bc683e2223bcf8c32588d34
1 #include <config.h>
2 #include <stdio.h>
4 /* Trivial example of reading a gzip'ed file or gzip'ed standard input
5 * using stdio functions fread(), getc(), etc... fseek() is not supported.
6 * Modify according to your needs. You can easily construct the symmetric
7 * zwrite program.
9 * Usage: zread [file[.gz]]
10 * This programs assumes that gzip is somewhere in your path.
12 int main(argc, argv)
13 int argc;
14 char **argv;
16 FILE *infile;
17 char cmd[256];
18 char buf[BUFSIZ];
19 int n;
21 if (argc < 1 || argc > 2) {
22 fprintf(stderr, "usage: %s [file[.gz]]\n", argv[0]);
23 exit(1);
25 strcpy(cmd, "gzip -dc "); /* use "gzip -c" for zwrite */
26 if (argc == 2) {
27 strncat(cmd, argv[1], sizeof(cmd)-strlen(cmd));
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(1);
34 /* Read one byte using getc: */
35 n = getc(infile);
36 if (n == EOF) {
37 pclose(infile);
38 exit(0);
40 putchar(n);
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);
48 if (pclose(infile) != 0) {
49 fprintf(stderr, "%s: pclose failed\n", argv[0]);
50 exit(1);
52 exit(0);
53 return 0; /* just to make compiler happy */