-
Notifications
You must be signed in to change notification settings - Fork 14
/
Task 36.c
97 lines (83 loc) · 1.8 KB
/
Task 36.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
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
// github.com/andy489
#include <stdlib.h>
#include <err.h>
#include <errno.h>
#include <string.h>
#include <stdint.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <fcntl.h>
#include <unistd.h>
#include <stdio.h>
int numerate = 0;
int cnt = 1;
void READ(int fd, const char * from){
char c;
ssize_t read_sz;
int newline = 1;
while((read_sz = read(fd, &c, 1)) > 0){
if(numerate) {
if(newline) {
setbuf(stdout, NULL);
fprintf(stdout, "%02d ", cnt);
write(1, &c, sizeof(c));
++cnt;
newline = 0;
}
else {
write(1, &c, sizeof(c));
}
if(c == '\n') newline = 1;
}
else write(1, &c, 1);
}
if(read_sz == -1){
int _errno=errno;
close(fd);
errno=_errno;
err(4,"error while reading %s", from);
}
/*
read ----> write
1)
printf(cnt)
setbuf(3)
write(c)
2)
char foo[10];
snprintf(foo...
write(FD, foo, n)
*/
}
int main(int argc, char ** argv){
if(argc == 1){
READ(0, "STDIN");
exit(0);
}
int i = 1;
if(strcmp(argv[i],"-n") == 0){
numerate = 1;
++i;
}
for(;i < argc; ++i){
if(strcmp("-", argv[i]) == 0){
READ(0, "STDIN");
continue;
}
const char * filepath = argv[i];
struct stat st;
if(stat(filepath, &st) == -1){
err(1, "error while stat %s", filepath);
}
if(!S_ISREG(st.st_mode)){
errx(2, "%s is nor regular file", filepath);
}
int fd = open(filepath, O_RDONLY);
if(fd == -1){
err(3,"error opening %s", filepath);
}
// exist, regular, readable
READ(fd, "filepath");
}
exit(0);
}