morpheus-base

morpheus base system
git clone git://git.2f30.org/morpheus-base
Log | Files | Refs

tee.c (845B)


      1 /* See LICENSE file for copyright and license details. */
      2 #include <stdio.h>
      3 #include <stdlib.h>
      4 #include <unistd.h>
      5 
      6 #include "util.h"
      7 
      8 static void
      9 usage(void)
     10 {
     11 	eprintf("usage: %s [-a] [file...]\n", argv0);
     12 }
     13 
     14 int
     15 main(int argc, char *argv[])
     16 {
     17 	int aflag = 0;
     18 	char buf[BUFSIZ];
     19 	int i, nfps;
     20 	size_t n;
     21 	FILE **fps = NULL;
     22 
     23 	ARGBEGIN {
     24 	case 'a':
     25 		aflag = 1;
     26 		break;
     27 	default:
     28 		usage();
     29 	} ARGEND;
     30 
     31 	nfps = argc + 1;
     32 	fps = ecalloc(nfps, sizeof *fps);
     33 
     34 	for (i = 0; argc > 0; argc--, argv++, i++)
     35 		if (!(fps[i] = fopen(*argv, aflag ? "a" : "w")))
     36 			eprintf("fopen %s:", *argv);
     37 	fps[i] = stdout;
     38 
     39 	while ((n = fread(buf, 1, sizeof buf, stdin)) > 0) {
     40 		for (i = 0; i < nfps; i++) {
     41 			if (fwrite(buf, 1, n, fps[i]) != n)
     42 				eprintf("%s: write error:", buf);
     43 		}
     44 	}
     45 	if (ferror(stdin))
     46 		eprintf("<stdin>: read error:");
     47 
     48 	return 0;
     49 }