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
98
99
100
101
102
|
#include "../lib/io/io.h"
#include "../lib/arg/arg.h"
#include "../lib/list/list.h"
#include "../lib/sys/errno.h"
#include "../lib/sys/types.h"
#include "../lib/tctl/tctl.h"
void mode_all(int fd);
void mode_singleline(int fd);
enum Modes {
MODE_ALL,
MODE_SINGLELINE,
MODE_SIZE
} mode = MODE_ALL;
char buf[BUFSIZ] = "";
list_t *files;
void(*mode_funcs[MODE_SIZE])(int fd) = {
mode_all,
mode_singleline
};
void add_file(const char *path)
{
list_append(files, (void*)path);
}
void add_stdin()
{
list_append(files, 0);
}
void set_singleline_mode()
{
mode = MODE_SINGLELINE;
}
void mode_all(int fd)
{
u64 rs;
while ((rs = read(fd, buf, BUFSIZ))) {
write(STDOUT_FD, buf, rs);
}
flush(STDOUT_FD);
}
void mode_singleline(int fd)
{
u64 rs;
u64 has_newline_char = 0;
char *p;
while (!has_newline_char) {
rs = read(fd, buf, BUFSIZ - 1);
for (p = buf; p < buf + rs; ++p) {
if (*p == '\n') {
has_newline_char = 1;
*(p + 1) = 0;
break;
}
}
wstd(buf);
}
}
int main(int argc, const char **argv)
{
list_node_t *file;
int fd;
files = new_list();
arg_register_default(&add_file);
arg_register_flag("-", &add_stdin);
arg_register_flag("-l", &set_singleline_mode);
arg_parse_arg(argc, argv);
if (files->size == 0) {
list_append(files, 0);
}
for (file = files->first; file; file = file->next) {
if (file->value)
fd = open(file->value, OPEN_READ_ONLY, 0);
else
fd = STDIN_FD;
if (fd < 0) {
wff(STDERR_FD, "read: %s\n", errstr[-fd]);
return -1;
}
mode_funcs[mode](fd);
}
free_list(files);
}
|