-
-
Notifications
You must be signed in to change notification settings - Fork 49
/
Copy pathtee.c
63 lines (55 loc) · 1.2 KB
/
tee.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
/**
* @brief tee - copy stdin to stdout and to specified files
*
* @copyright
* This file is part of ToaruOS and is released under the terms
* of the NCSA / University of Illinois License - see LICENSE.md
* Copyright (C) 2018 K. Lange
*/
#include <stdio.h>
#include <unistd.h>
#include <getopt.h>
#include <signal.h>
#include <string.h>
#include <errno.h>
int main(int argc, char * argv[]) {
int append = 0;
int ret_val = 0;
int opt;
while ((opt = getopt(argc, argv, "ai")) != -1) {
switch (opt) {
case 'a':
append = 1;
break;
case 'i':
signal(SIGINT, SIG_IGN);
break;
}
}
int file_count = argc - optind;
FILE ** files = malloc(sizeof(FILE *) * file_count);
for (int i = 0, j = optind; j < argc && i < file_count; j++) {
files[i] = fopen(argv[j], append ? "a" : "w");
if (!files[i]) {
fprintf(stderr, "%s: %s: %s\n", argv[0], argv[j], strerror(errno));
ret_val = 1;
file_count--;
continue;
} else {
i++;
}
}
while (!feof(stdin)) {
int c = fgetc(stdin);
if (c >= 0) {
fputc(c, stdout);
for (int i = 0; i < file_count; ++i) {
fputc(c, files[i]);
}
}
}
for (int i = 0; i < file_count; ++i) {
fclose(files[i]);
}
return ret_val;
}