기초 리눅스 API vol.1 연습문제 풀어보기 (4장)
2021. 2. 23. 13:29ㆍLinux API
4장 (159pg)
4-1.
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
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
|
#include <sys/stat.h>
#include <fcntl.h>
#include <ctype.h>
#include "../lib/tlpi_hdr.h"
/* [교재] 기초 리눅스 API vol.1 (4. 10 연습문제 // 4-1)
*
* tee 명령은 EOF까지 표준 입력을 읽고, 입력 내용을 그대로 표준 출력과 명령행 인자로 지정된 파일로 내보낸다.
* 기본적으로 tee는 주어진 이름의 파일이 존재하면 모두 덮어쓴다(overwrite).
* 파일이 이미 존재하는 경우 tee가 그 끝에 이어 쓰도록(append) 하는 -a 명령행 옵션(tee -a file)을 구현하라.
*/
#define printable(ch) (isprint((unsigned char) ch) ? ch : '#')
#define BUF_SIZE 256
extern int optind, opterr, optopt;
extern char *optarg;
static void /* '사용법' 메시지를 출력하고 종료한다. */
usageError(char *progName, char *msg, int opt)
{
if (msg != NULL && opt != 0)
fprintf(stderr, "%s (-%c)\n", msg, printable(opt));
fprintf(stderr, "Usage: %s [-a] file\n", progName);
exit(EXIT_FAILURE);
}
int
main(int argc, char *argv[])
{
int opt;
char *pstr;
int fd, flag;
mode_t mode;
ssize_t numRead;
char buf[BUF_SIZE];
pstr = NULL;
if (argc == 1 || strcmp(argv[1], "--help") == 0)
usageError(argv[0], NULL, 0);
while((opt = getopt(argc, argv, ":a:")) != -1)
{
switch (opt)
{
case 'a' : pstr = optarg; break;
case ':' : usageError(argv[0], "Missing argument", optopt);
case '?' : usageError(argv[0], "Unrecognize option", optopt);
default : fatal("Unexpected case in switch()");
}
}
if (pstr != NULL)
flag = O_WRONLY | O_CREAT | O_APPEND;
if (optind < argc)
{
flag = O_WRONLY | O_CREAT | O_TRUNC;
pstr = argv[optind];
}
mode = S_IRUSR | S_IWUSR | S_IRGRP | S_IWGRP |
S_IROTH | S_IWOTH; /* rw-rw-rw- */
fd = open(pstr, flag, mode);
if (fd == -1)
errExit("open");
while((numRead = read(STDIN_FILENO, buf, BUF_SIZE)) > 0)
{
if (write(STDOUT_FILENO, buf, numRead) != numRead)
fatal("[STDOUT_FILENO] couldn't write whole buffer");
if (write(fd, buf, numRead) != numRead)
fatal("[%s] couldn't write whole buffer", pstr);
}
if (numRead == -1)
errExit("read");
if (close(fd) == -1)
errExit("close");
exit(EXIT_SUCCESS);
}
|
cs |