From 35f0578cea7c44efe0e643c611082b656a788fe2 Mon Sep 17 00:00:00 2001 From: g1n Date: Fri, 12 Aug 2022 10:52:05 +0300 Subject: [PATCH] Add tee util --- src/tee.c | 50 ++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 50 insertions(+) create mode 100644 src/tee.c diff --git a/src/tee.c b/src/tee.c new file mode 100644 index 0000000..46f74c9 --- /dev/null +++ b/src/tee.c @@ -0,0 +1,50 @@ +#include +#include +#include +#include + +int usage(char *argv0) { + printf("Usage: %s [-ai] [file ...]\n", argv0); + return 2; +} + +int main(int argc, char *argv[]){ + int opt; + bool append = false; + bool iflag = false; + while ((opt = getopt(argc, argv, ":ai")) != -1) { + switch (opt) { + case 'a': + append = true; + break; + case 'i': + iflag = true; + break; + case '?': + fprintf(stderr, "%s: invalid option -- '%c'\n", argv[0], optopt); + return usage(argv[0]); + } + } + + if (iflag && signal(SIGINT, SIG_IGN) == SIG_ERR) {} // FIXME + + int arg = optind; + void *buf[BUFSIZ]; + FILE *file; + ssize_t n; + + while ((n = read(0, buf, sizeof(buf))) > 0) { + optind = arg; + if (optind < argc) { + for (; optind < argc; optind++) { + file = fopen(argv[optind], append ? "w" : "a+"); + fwrite(buf, BUFSIZ, 1, file); + fclose(file); + append = true; + } + } else { + fwrite(buf, BUFSIZ, 1, stdout); + } + } + return 0; +}