1/* See LICENSE file for copyright and license details. */
2
3
4#include <fcntl.h>
5#include <signal.h>
6#include <unistd.h>
7
8#include "util.h"
9
10static void
11usage(void)
12{
13 eprintf("usage: %s [-ai] [file ...]\n", argv0);
14}
15
16// ?man tee: duplicate input
17// ?man arguments: file ...
18// ?man read from standard input and write to standard output and files
19int
20main(int argc, char *argv[])
21{
22 int *fds = NULL;
23 size_t i, nfds;
24 ssize_t n;
25 int ret = 0, aflag = O_TRUNC, iflag = 0;
26 char buf[BUFSIZ];
27
28 ARGBEGIN {
29 // ?man -a: print or show all entries
30 case 'a':
31 aflag = O_APPEND;
32 break;
33 // ?man -i: interactive mode or prompt for confirmation
34 case 'i':
35 iflag = 1;
36 break;
37 default:
38 usage();
39 } ARGEND
40
41 if (iflag && signal(SIGINT, SIG_IGN) == SIG_ERR)
42 eprintf("signal:");
43 nfds = argc + 1;
44 fds = ecalloc(nfds, sizeof(*fds));
45
46 for (i = 0; i < (size_t)argc; i++) {
47 if ((fds[i] = open(argv[i], O_WRONLY|O_CREAT|aflag, 0666)) < 0) {
48 weprintf("open %s:", argv[i]);
49 ret = 1;
50 }
51 }
52 fds[i] = 1;
53
54 while ((n = read(0, buf, sizeof(buf))) > 0) {
55 for (i = 0; i < nfds; i++) {
56 if (fds[i] >= 0 && writeall(fds[i], buf, n) < 0) {
57 weprintf("write %s:", (i != (size_t)argc) ? argv[i] : "<stdout>");
58 fds[i] = -1;
59 ret = 1;
60 }
61 }
62 }
63 if (n < 0)
64 eprintf("read <stdin>:");
65
66 return ret;
67}