tests: help-version: cross-check PATH in tests
[gzip.git] / sample / zread.c
blobe20de49a35f43d51633b4f424c0f1c54f5ac288f
1 #include <config.h>
2 #include <stdio.h>
3 #include <stdlib.h>
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.
10 * Usage: zread [file[.gz]]
11 * This programs assumes that gzip is somewhere in your path.
13 int main(argc, argv)
14 int argc;
15 char **argv;
17 FILE *infile;
18 char cmd[256];
19 char buf[BUFSIZ];
20 int n;
22 if (argc < 1 || argc > 2) {
23 fprintf(stderr, "usage: %s [file[.gz]]\n", argv[0]);
24 exit(EXIT_FAILURE);
26 strcpy(cmd, "gzip -dc "); /* use "gzip -c" for zwrite */
27 if (argc == 2) {
28 strncat(cmd, argv[1], sizeof(cmd)-strlen(cmd));
30 infile = popen(cmd, "r"); /* use "w" for zwrite */
31 if (infile == NULL) {
32 fprintf(stderr, "%s: popen('%s', 'r') failed\n", argv[0], cmd);
33 exit(EXIT_FAILURE);
35 /* Read one byte using getc: */
36 n = getc(infile);
37 if (n == EOF) {
38 pclose(infile);
39 exit(EXIT_SUCCESS);
41 putchar(n);
43 /* Read the rest using fread: */
44 for (;;) {
45 n = fread(buf, 1, BUFSIZ, infile);
46 if (n <= 0) break;
47 fwrite(buf, 1, n, stdout);
49 if (pclose(infile) != 0) {
50 fprintf(stderr, "%s: pclose failed\n", argv[0]);
51 exit(EXIT_FAILURE);
53 exit(EXIT_SUCCESS);
54 return 0; /* just to make compiler happy */