sbase/tee.c

62 lines
1.1 KiB
C
Raw Normal View History

2011-05-22 21:36:34 -04:00
/* See LICENSE file for copyright and license details. */
2015-01-22 16:08:25 -05:00
#include <signal.h>
2011-05-22 21:36:34 -04:00
#include <stdio.h>
2011-05-22 21:36:34 -04:00
#include "util.h"
2013-06-14 14:20:47 -04:00
static void
usage(void)
{
eprintf("usage: %s [-ai] [file ...]\n", argv0);
2013-06-14 14:20:47 -04:00
}
2011-05-22 21:36:34 -04:00
int
main(int argc, char *argv[])
{
FILE **fps = NULL;
size_t i, n, nfps;
int ret = 0, aflag = 0, iflag = 0;
2013-06-14 14:20:47 -04:00
char buf[BUFSIZ];
2011-05-22 21:36:34 -04:00
2013-06-14 14:20:47 -04:00
ARGBEGIN {
case 'a':
aflag = 1;
2013-06-14 14:20:47 -04:00
break;
2015-01-22 16:08:25 -05:00
case 'i':
iflag = 1;
break;
2013-06-14 14:20:47 -04:00
default:
usage();
} ARGEND
2013-06-14 14:20:47 -04:00
2015-01-22 16:08:25 -05:00
if (iflag && signal(SIGINT, SIG_IGN) == SIG_ERR)
eprintf("signal:");
nfps = argc + 1;
fps = ecalloc(nfps, sizeof(*fps));
2016-06-23 14:37:23 -04:00
for (i = 0; i < argc; i++) {
if (!(fps[i] = fopen(argv[i], aflag ? "a" : "w"))) {
weprintf("fopen %s:", argv[i]);
ret = 1;
}
}
fps[i] = stdout;
2011-05-22 21:36:34 -04:00
while ((n = fread(buf, 1, sizeof(buf), stdin))) {
for (i = 0; i < nfps; i++) {
2016-06-23 14:37:23 -04:00
if (fps[i] && fwrite(buf, 1, n, fps[i]) != n) {
fshut(fps[i], (i != argc) ? argv[i] : "<stdout>");
fps[i] = NULL;
ret = 1;
}
2013-06-14 14:20:47 -04:00
}
}
2016-06-23 14:37:23 -04:00
ret |= fshut(stdin, "<stdin>");
for (i = 0; i < nfps; i++)
if (fps[i])
ret |= fshut(fps[i], (i != argc) ? argv[i] : "<stdout>");
return ret;
2011-05-22 21:36:34 -04:00
}