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
|
#include "sort.h"
int main(void) {
vec *lines;
unsigned long i;
char *line;
lines = vec_init();
while ((line = read_line(stdin)) != NULL) {
vec_add(lines, line);
}
free(line);
qsort(lines->data, lines->count, sizeof(char *), qsort_strcmp);
for (i = 0; i < lines->count; i++) {
fputs(lines->data[i], stdout);
}
vec_free(lines);
exit(EXIT_SUCCESS);
}
char *read_line(FILE* stream) {
char *buf;
char *line;
unsigned long line_length;
unsigned long line_size;
line_size = BUF_SIZE;
line = malloc(line_size * sizeof(char *));
strncpy(line, "", 1);
buf = malloc(BUF_SIZE);
for (;;) {
if (fgets(buf, BUF_SIZE, stream) == NULL) {
free(buf);
free(line);
return NULL;
}
line = strncat(line, buf, BUF_SIZE);
line_length = strlen(line);
if (line[line_length - 1] == '\n') {
free(buf);
return line;
} else {
line_size <<= 1;
line = realloc(line, line_size * sizeof(char *));
}
}
}
vec *vec_init(void) {
vec *v;
v = malloc(sizeof(vec));
v->count = 0;
v->size = VEC_SIZE;
v->data = malloc(v->size * sizeof(char *));
return v;
}
void vec_add(vec *v, char *s) {
if (v->count == v->size) {
v->size <<= 1;
v->data = realloc(v->data, v->size * sizeof(char *));
}
v->data[v->count++] = s;
return;
}
void vec_free(vec *v) {
unsigned long i;
for (i = 0; i < v->count; i++) {
free(v->data[i]);
}
free(v->data);
free(v);
return;
}
static int qsort_strcmp(const void *p1, const void *p2) {
return strcmp(* (char * const *) p1, * (char * const *) p2);
}
|