tests: reference: don't rely on od's -w option
[gzip.git] / sample / zread.c
blobe38095cc793e1252993626de7ae79ebacb45a612
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
14 main (int argc, 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(EXIT_FAILURE);
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(EXIT_FAILURE);
34 /* Read one byte using getc: */
35 n = getc(infile);
36 if (n == EOF) {
37 pclose(infile);
38 exit(EXIT_SUCCESS);
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(EXIT_FAILURE);
52 exit(EXIT_SUCCESS);
53 return 0; /* just to make compiler happy */