-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path4-1-tee.c
67 lines (50 loc) · 1.2 KB
/
4-1-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
64
65
66
67
#include <stdio.h>
#include <fcntl.h>
#include <unistd.h>
int
main(int argc ,char *argv[]){
int ch = 0;
int has_file = 0;
int append = 0;
int ret = 0;
char buf[1024];
int read_num = 0;
const char* help = "Usage: tee [OPTION]... [FILE]...\n"
"\ta: append to the given FILEs, do not overwrite\n"
"\th: display this help and exit\n";
/* parse and process options */
while ((ch = getopt(argc, argv, "ah")) != -1)
{
switch (ch)
{
case 'a':
append = 1;
break;
case 'h':
default:
printf("%s", help);
return 0;
}
}
if(append && argc > 2){
ret = open(argv[argc-1],O_RDWR | O_APPEND);
has_file = 1;
}
else if(argc>1){
ret = open(argv[argc-1],O_RDWR);
has_file = 1;
}
if(has_file && ret==-1){
perror("open error");
return 0;
}
while(1){
while((read_num = read(STDIN_FILENO,buf,1024))>0){
write(STDOUT_FILENO,buf,read_num);
if(has_file){
write(ret,buf,read_num);
}
}
}
return 0;
}