-
Notifications
You must be signed in to change notification settings - Fork 0
/
test.c
84 lines (70 loc) · 1.43 KB
/
test.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
#include <stdio.h>
#include <string.h>
#include <termio.h>
#include <sys/ioctl.h>
#include "trie.h"
void find_and_print(Trie_typ* trie, char* to_find)
{
StringNode_typ* results = Trie_find(trie, to_find);
StringNode_typ* iter = results;
int max = 10;
iterate(iter) {
if (iter->value) {
printf("%s\n", iter->value);
if (--max < 0) {
break;
}
}
}
StringNode_free(results);
}
int main(int argc, char** argv)
{
if (!strcmp(argv[1], "load")) {
FILE* file = fopen("trie-data", "r");
Trie_typ* loaded = Trie_load(file);
struct termios oldT, newT;
ioctl(0, TCGETS, &oldT);
newT = oldT;
newT.c_lflag &= ~(ECHO | ICANON);
ioctl(0, TCSETS, &newT);
char word[1024];
int pos = 0;
while (1) {
char c;
read(0, &c, 1);
if (c == '/') {
pos = 0;
memset(word, 0, 1024);
} else if (c == '?') {
Trie_destroy(loaded);
fclose(file);
return 0;
} else {
word[pos++] = c;
word[pos] = '\0';
find_and_print(loaded, word);
}
}
return 0;
}
Trie_typ* trie = Trie_init();
char word[1024];
while (fgets(word, 1024-1, stdin)) {
word[strlen(word)-1] = '\0'; // replace the newline
Trie_add(trie, word);
}
if (!strcmp(argv[1], "build")) {
FILE* stream = fopen("trie-data", "w");
if (stream) {
Trie_save(trie, stream);
fclose(stream);
} else {
printf("Error occurred\n");
}
}
find_and_print(trie, argv[1]);
Trie_destroy(trie);
trie = NULL;
return 0;
}