micro-utils/src/tee.c

62 lines
1.1 KiB
C
Raw Normal View History

2024-07-01 10:23:00 +00:00
#include <fcntl.h>
#include <stdio.h>
#include <errno.h>
#include <string.h>
#include <signal.h>
#include <unistd.h>
#include <stdlib.h>
#include "config.h"
int main(int argc, char **argv) {
int flag = O_TRUNC;
int opt;
while ((opt = getopt(argc, argv, "ai")) != -1) {
switch (opt) {
case 'a':
flag = O_APPEND;
break;
case 'i':
signal(SIGINT, SIG_IGN);
break;
default:
2024-07-03 14:22:50 +00:00
puts("tee [ai] [file]\n\t-a Append\n\t-i Ignore interrupt signals");
2024-07-01 10:23:00 +00:00
return 0;
}
}
argv += optind;
argc -= optind;
int fd = STDOUT_FILENO;
if (argc > 0 && strcmp(argv[0], "-")) {
fd = open(argv[0], O_WRONLY | flag | O_CREAT, 0666);
if (fd < 0) {
fprintf(stderr, "tee: %s\n", strerror(errno));
return 1;
}
}
char buf[BUF_SIZE + 1];
ssize_t bytes = 0;
while ((bytes = read(STDIN_FILENO, buf, sizeof(buf)))) {
int stat = write(STDOUT_FILENO, buf, bytes);
int stat2 = bytes;
if (argc > 0)
stat2 = write(fd, buf, bytes);
if (stat != bytes || stat2 != bytes) {
fprintf(stderr, "tee: %s\n", strerror(errno));
return 1;
}
}
if (argc > 0 && strcmp(argv[0], "-"))
close(fd);
return 0;
}