-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path5.07-sort.c
112 lines (91 loc) · 2.2 KB
/
5.07-sort.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
#include <assert.h>
#include <stdbool.h>
#include <stdio.h>
#include <stdlib.h>
#include "lib/dynarray.h"
#include "lib/heap.h"
#include "lib/readline.h"
#include "lib/strncopy.h"
#define MAXLEN 8
#define MAXLINES 8
struct sorter {
struct dynarray *q;
};
struct sorter *sorter_alloc(void) {
struct sorter *s = malloc(sizeof(struct sorter));
if (s == NULL) {
return NULL;
}
s->q = dynarray_alloc(0);
if (s->q == NULL) {
free(s);
return NULL;
}
return s;
}
void sorter_free(struct sorter *s) {
assert(s != NULL);
for (int i = 0; i < dynarray_len(s->q); i++) {
free(dynarray_get(s->q, i));
}
dynarray_free(s->q);
free(s);
}
bool sorter_push(struct sorter *s, char *buf, size_t len) {
assert(s != NULL);
char *line = malloc((len + 1) * sizeof(char *));
if (line == NULL) {
return false;
}
strncopy(line, buf, len);
line[len] = '\0';
bool ok = heap_push(s->q, line);
if (!ok) {
free(line);
return false;
}
return true;
}
char *sorter_pop(struct sorter *s) {
assert(s != NULL);
if (!dynarray_len(s->q)) {
return NULL;
}
return heap_pop(s->q);
}
int main() {
char buf[MAXLEN];
struct sorter *s = sorter_alloc();
if (s == NULL) {
fprintf(stderr, "error: failed to allocate sorter\n");
return EXIT_FAILURE;
}
for (int i = 0; i < MAXLINES; i++) {
int nread = readline(buf, MAXLEN, stdin);
if (nread < 0) {
sorter_free(s);
fprintf(stderr, "error: line too long\n");
return EXIT_FAILURE;
}
if (nread > 0) {
bool ok = sorter_push(s, buf, nread);
if (!ok) {
sorter_free(s);
fprintf(stderr, "error: failed to push to sorter\n");
return EXIT_FAILURE;
}
continue;
}
assert(!nread);
char *line;
while ((line = sorter_pop(s))) {
printf("%s", line);
free(line);
}
sorter_free(s);
return EXIT_SUCCESS;
}
sorter_free(s);
fprintf(stderr, "error: too many lines\n");
return EXIT_FAILURE;
}