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
|
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
#include <stdio.h>
#include <fcntl.h>
#include <stdlib.h>
#define MAX_BUFFER 1024
int main(int argc,char** argv){
int fd,readbyte;
char buffer[MAX_BUFFER];
if(argc != 2){
printf("Usage:mytee FILE\n");
exit(EXIT_FAILURE);
}
fd = open(argv[1],O_CLOEXEC|O_WRONLY|O_CREAT|O_TRUNC,S_IRUSR|S_IWUSR|S_IRGRP|S_IWGRP|S_IROTH);
if(fd == -1){
perror("open failed!");
}
while(1){
readbyte = read(STDIN_FILENO,buffer,MAX_BUFFER);
if(readbyte == 0){
break;
}
if(write(STDOUT_FILENO,buffer,readbyte) == -1){
perror("write to stdout failed!");
}
if(write(fd,buffer,readbyte) == -1){
perror("write to file failed!");
}
}
if(readbyte < 0){
perror("read from stdin failed!");
}
close(fd);
return EXIT_SUCCESS;
}
|