NetBSD/distrib/utils/zcat/zcat.c

134 lines
2.5 KiB
C

/* $NetBSD: zcat.c,v 1.4 2011/05/19 22:23:12 tsutsui Exp $ */
/* mini zcat.c -- a minimal zcat using the zlib compression library
* Copyright (C) 1995-1996 Jean-loup Gailly.
* For conditions of distribution and use, see copyright notice in zlib.h
*/
/*
* Credits, History:
* This program is a reduced version of the minigzip.c
* program originally written by Jean-loup Gailly.
* This reduction is the work of Gordon Ross.
*/
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include "zlib.h"
#define BUFLEN 4096
char *prog;
void error(const char *msg);
void gz_uncompress(gzFile in, FILE *out);
int main(int argc, char *argv[]);
/* ===========================================================================
* Display error message and exit
*/
void error(const char *msg)
{
fprintf(stderr, "%s: %s\n", prog, msg);
exit(EXIT_SUCCESS);
}
/* ===========================================================================
* Uncompress input to output then close both files.
*/
void gz_uncompress(gzFile in, FILE *out)
{
char buf[BUFLEN];
int len;
int err;
for (;;) {
len = gzread(in, buf, sizeof(buf));
if (len < 0)
error (gzerror(in, &err));
if (len == 0)
break;
if ((int)fwrite(buf, 1, (unsigned)len, out) != len) {
error("failed fwrite");
}
}
if (fclose(out))
error("failed fclose");
if (gzclose(in) != Z_OK)
error("failed gzclose");
}
/* ===========================================================================
* Usage: zcat [files...]
*/
int main(int argc, char *argv[])
{
gzFile zfp;
/* save program name and skip */
prog = argv[0];
argc--, argv++;
/* ignore any switches */
while (*argv && (**argv == '-')) {
argc--, argv++;
}
if (argc == 0) {
zfp = gzdopen(fileno(stdin), "rb");
if (zfp == NULL)
error("can't gzdopen stdin");
gz_uncompress(zfp, stdout);
return 0;
}
do {
/* file_uncompress(*argv); */
zfp = gzopen(*argv, "rb");
if (zfp == NULL) {
fprintf(stderr, "%s: can't gzopen %s\n", prog, *argv);
exit(EXIT_FAILURE);
}
gz_uncompress(zfp, stdout);
} while (argv++, --argc);
return 0; /* to avoid warning */
}
/*
* XXX: hacks to keep gzio.c from pulling in deflate stuff
*/
int deflateInit2_(z_streamp strm, int level, int method,
int windowBits, int memLevel, int strategy,
const char *version, int stream_size)
{
return -1;
}
int deflate(z_streamp strm, int flush)
{
return -1;
}
int deflateEnd(z_streamp strm)
{
return -1;
}
int deflateParams(z_streamp strm, int level, int strategy)
{
return Z_STREAM_ERROR;
}