-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtee.c
49 lines (49 loc) · 1.49 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
/*
Implementing the Linux tee instruction with C.
The additional libray "tlpi_hdr.h"
can be found on https://man7.org/tlpi/code/online/all_files_by_chapter.html
*/
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
#include "tlpi_hdr.h"
#ifndef BUF_SIZE
#define BUF_SIZE 1024
#endif
int
main(int argc, char const *argv[])
{
// tee code
int fd, openFlags, opt;
mode_t filePerms;
ssize_t numRead, numWritten, numWritten2;
char buf[BUF_SIZE+1];
if (argc<2){
usageErr("Usage: %s [-a] output-filename\n", argv[0]);
}
openFlags = O_CREAT | O_WRONLY | O_TRUNC;
while ((opt = getopt(argc, argv, ":a")) != -1) {
switch (opt) {
case 'a':
openFlags = O_CREAT | O_WRONLY | O_APPEND;
break;
case '?':
usageErr("Usage: %s [-a] output-filename\n", argv[0]);
}
}
filePerms = S_IRUSR | S_IWUSR | S_IRGRP | S_IWGRP | S_IROTH | S_IWOTH;
fd = open(argv[argc-1], openFlags, filePerms);
if (fd == -1)
errExit("opening file %s\n", argv[argc-1]);
while ((numRead= read (STDIN_FILENO, buf, BUF_SIZE)) != 0){
numWritten = write(fd, buf, numRead);
numWritten2 = write(STDOUT_FILENO, buf, numRead);
if (numWritten != numRead)
errExit("write file %s\n",argv[argc-1]);
if (numWritten2 != numRead)
errExit("stdout\n");
}
if (close(fd) == -1)
errExit("close file %s error\n",argv[argc-1]);
return 0;
}