FENIX_coreutils/tee.c

58 lines
No EOL
1.3 KiB
C

#define _POSIX_C_SOURCE 200809L
#include <stdio.h>
#include <stdlib.h>
#include <signal.h>
#include <string.h>
#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;
}
}
while(strcmp("-a", argv[start_arg]) == 0 ||
strcmp("-i", argv[start_arg]) == 0 ||
strcmp("-ai", argv[start_arg]) == 0 ||
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;
}
}
while((c = getchar()) != EOF) {
putchar(c);
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;
}