-
Notifications
You must be signed in to change notification settings - Fork 0
/
5.13-tail.c
123 lines (104 loc) · 2.54 KB
/
5.13-tail.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
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
#include <assert.h>
#include <errno.h>
#include <stdlib.h>
#include "lib/deque.h"
#include "lib/readline.h"
#include "lib/strncopy.h"
#define MAXLEN 8
struct tailer {
struct deque *d;
size_t numlines;
};
struct tailer *tailer_alloc(size_t numlines) {
struct tailer *t = malloc(sizeof(struct tailer));
if (t == NULL) {
return NULL;
}
t->d = deque_alloc();
if (t->d == NULL) {
free(t);
return NULL;
}
t->numlines = numlines;
return t;
}
void tailer_free(struct tailer *t) {
assert(t != NULL);
while (deque_len(t->d)) {
free(deque_pop(t->d));
}
deque_free(t->d);
free(t);
}
bool tailer_push(struct tailer *t, char *buf, size_t len) {
assert(t != NULL);
char *line = malloc((len + 1) * sizeof(char));
if (line == NULL) {
return false;
}
strncopy(line, buf, len);
line[len] = '\0';
bool ok = deque_append(t->d, line);
if (!ok) {
free(line);
return false;
}
if (deque_len(t->d) > t->numlines) {
free(deque_popleft(t->d));
}
return true;
}
char *tailer_pop(struct tailer *t) {
assert(t != NULL);
if (!deque_len(t->d)) {
return NULL;
}
return deque_popleft(t->d);
}
int main(int argc, char *argv[]) {
if (argc != 2) {
fprintf(stderr, "usage: %s NUMLINES\n", argv[0]);
return EXIT_FAILURE;
}
char *end = NULL;
errno = 0;
long numlines = strtol(argv[1], &end, 10);
if (*end != '\0') {
fprintf(stderr, "error: numlines is not a number\n");
return EXIT_FAILURE;
}
if (errno == ERANGE) {
fprintf(stderr, "error: numlines is out of range\n");
return EXIT_FAILURE;
}
assert(!errno);
struct tailer *t = tailer_alloc(numlines);
if (t == NULL) {
fprintf(stderr, "error: failed to allocate tailer\n");
return EXIT_FAILURE;
}
char buf[MAXLEN];
int nread;
while ((nread = readline(buf, MAXLEN, stdin))) {
if (nread < 0) {
tailer_free(t);
fprintf(stderr, "error: line too long\n");
return EXIT_FAILURE;
}
if (nread > 0) {
bool ok = tailer_push(t, buf, nread);
if (!ok) {
tailer_free(t);
fprintf(stderr, "error: failed to push to tailer\n");
return EXIT_FAILURE;
}
}
}
char *line;
while ((line = tailer_pop(t))) {
printf("%s", line);
free(line);
}
tailer_free(t);
return EXIT_SUCCESS;
}