FENIX_coreutils/tee.c

66 lines
1.4 KiB
C
Raw Normal View History

2020-12-11 10:42:12 +00:00
#include <stdio.h>
#include <stdlib.h>
#include <signal.h>
#include <string.h>
/*
Why is it always the fucking GNU Project causing
problems?! For fuck's sake!
-Kat
*/
#ifdef __GLIBC__
#define __USE_POSIX2
#endif
#include <unistd.h>
int main(int argc, char * argv[]) {
char c; int start_arg = 1;
int append_mode = 0;
int file_failed = 0;
while((c = getopt(argc, argv, "ai")) != -1) {
switch(c) {
case 'a': append_mode = 1; break;
case 'i': signal(SIGINT, SIG_IGN); break;
}
}
2020-12-11 10:47:28 +00:00
while(strcmp("-a", argv[start_arg]) == 0 ||
strcmp("-i", argv[start_arg]) == 0 ||
strcmp("-ai", argv[start_arg]) == 0 ||
2020-12-11 10:42:12 +00:00
strcmp("-ia", argv[start_arg]) == 0) {
start_arg++;
}
FILE * files[27] = { 0 };
char * mode = append_mode == 1 ? "a+" : "w+";
int j = 0;
for(int i = start_arg; i < argc && j < 27; i++) {
files[j++] = fopen(argv[i], mode);
if(files == NULL) {
fprintf(stderr, "%s: could not open/create file %s\n", argv[0], argv[i]);
return 1;
2020-12-11 10:42:12 +00:00
}
}
while((c = getchar()) != EOF) {
putchar(c);
2020-12-11 10:42:12 +00:00
for(j = 0; files[j] != 0 && j < 27; j++) {
if(fputc(c, files[j]) == EOF) {
file_failed = 1;
}
}
}
for(j = 0; files[j] != 0 && j < 27; j++) {
if(fclose(files[j]) == EOF) {
fprintf(stderr, "%s: failed to close file %s\n",
argv[0], argv[j+start_arg]);
}
}
return file_failed == 0 ? 0 : 2;
2020-12-11 10:42:12 +00:00
}