xref: /original-bsd/usr.bin/tee/tee.c (revision 1aa52444)
1 /*
2  * Copyright (c) 1988 Regents of the University of California.
3  * All rights reserved.
4  *
5  * Redistribution and use in source and binary forms are permitted
6  * provided that the above copyright notice and this paragraph are
7  * duplicated in all such forms and that any documentation,
8  * advertising materials, and other materials related to such
9  * distribution and use acknowledge that the software was developed
10  * by the University of California, Berkeley.  The name of the
11  * University may not be used to endorse or promote products derived
12  * from this software without specific prior written permission.
13  * THIS SOFTWARE IS PROVIDED ``AS IS'' AND WITHOUT ANY EXPRESS OR
14  * IMPLIED WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED
15  * WARRANTIES OF MERCHANTIBILITY AND FITNESS FOR A PARTICULAR PURPOSE.
16  */
17 
18 #ifndef lint
19 char copyright[] =
20 "@(#) Copyright (c) 1988 Regents of the University of California.\n\
21  All rights reserved.\n";
22 #endif /* not lint */
23 
24 #ifndef lint
25 static char sccsid[] = "@(#)tee.c	5.5 (Berkeley) 07/10/88";
26 #endif /* not lint */
27 
28 #include <sys/types.h>
29 #include <sys/file.h>
30 #include <signal.h>
31 #include <stdio.h>
32 
33 main(argc, argv)
34 	int argc;
35 	char **argv;
36 {
37 	extern int optind;
38 	register int cnt, n, step;
39 	int append, ch, *fd;
40 	char buf[8192], *malloc();
41 	off_t lseek();
42 
43 	append = 0;
44 	while ((ch = getopt(argc, argv, "ai")) != EOF)
45 		switch((char)ch) {
46 		case 'a':
47 			append = 1;
48 			break;
49 		case 'i':
50 			(void)signal(SIGINT, SIG_IGN);
51 			break;
52 		case '?':
53 		default:
54 			fprintf(stderr, "usage: tee [-ai] [file ...]\n");
55 			exit(2);
56 		}
57 	argv += optind;
58 	argc -= optind;
59 
60 	if (!(fd = (int *)malloc((u_int)((argc + 1) * sizeof(int))))) {
61 		fprintf(stderr, "tee: out of space.\n");
62 		exit(2);
63 	}
64 	fd[0] = 1;			/* always write to stdout */
65 	for (cnt = 1; *argv; ++argv)
66 		if ((fd[cnt] = open(*argv, append ? O_WRONLY|O_CREAT :
67 		    O_WRONLY|O_CREAT|O_TRUNC, 0600)) < 0) {
68 			fprintf(stderr, "tee: %s: ", *argv);
69 			perror((char *)NULL);
70 		}
71 		else {
72 			if (append)
73 				(void)lseek(fd[cnt], 0L, L_XTND);
74 			++cnt;
75 		}
76 	for (--cnt; (n = read(0, buf, sizeof(buf))) > 0;)
77 		for (step = cnt; step >= 0; --step)
78 			(void)write(fd[step], buf, n);
79 	exit(0);
80 }
81