Add tee util

This commit is contained in:
g1n 2022-08-12 10:52:05 +03:00
parent 44cbb98694
commit 35f0578cea
Signed by: g1n
GPG Key ID: 8D352193D65D4E2C
1 changed files with 50 additions and 0 deletions

50
src/tee.c Normal file
View File

@ -0,0 +1,50 @@
#include <stdbool.h>
#include <stdio.h>
#include <signal.h>
#include <unistd.h>
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;
}