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
|
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
#include <string.h>
#include "read.h"
#include "strbst.h"
#include "nodelink.h"
#include "ll.h"
void consumespaces(FILE* file) {
// used to consume spaces in an item ("- list item" -> "list item")
int c;
while ( ( c = fgetc(file) ) != EOF && c == ' ' );
ungetc(c, file);
}
void wsclean(char* txt, size_t sz){ // "string \n \n" -> "string\n\n"
int nl = 0; // count of newlines
size_t i;
for (i = sz-1; i >= 0; i--) { // start at end [i-1] and dec
if (txt[i] == '\n') nl++; // count up newlines
else if (txt[i] != ' ') break; // and break on unpadded text
}
memset(txt+i, '\n', nl); // add #nl newlines at [i, i+nl)
txt[i+nl] = 0; // finish string
}
char* empty(void) {
// "" with a freeable memory address
char* str = malloc(sizeof(char));
*str = 0;
return str;
}
char* line(FILE* file) { // gets a line from file
char* link = NULL;
size_t n = 0;
getline(&link, &n, file); // getline stores a line of size n in link
wsclean(link, n); // removes trailing whitespace
if (*link == '\n') { // empty line treated as ""
free(link);
char* out = empty(); // DEBGUGU
return out;
} else { // else return obtained
return link;
}
}
link* insorget(strbst* tgt, char* name) {
link* get = query(tgt, name);
if (!get) {
get = newlink(newnode());
insbst(tgt, name, get);
}
return get;
}
link* addbstlink(strbst* tree, char* name, node* to) {
link* l = newlink(to);
insbst(tree, name, l);
return l;
}
char* resolvell(llnode* head, size_t* sz) {
llnode* tail = head->next;
head->next = NULL;
char *out, *pos;
pos = out = malloc(sizeof(char)*(*sz+1)); out[*sz] = 0;
*sz = 0;
while (tail != NULL) {
size_t len = strlen(tail->str);
memcpy(pos, tail->str, len);
pos += len;
llnode* tmp = tail;
tail = tail->next;
free(tmp->str); free(tmp);
}
return out;
}
node* readfile(char* name) {
FILE* read = fopen(name, "r");
node *root, *cur;
cur = root = newnode();
link* curl = addbstlink(root->links, name, root);
llnode start;
start.next = NULL; // empty desc isn't undefined
llnode *head, *tail;
head = tail = &start;
size_t sz = 0;
int c;
while ( ( c = fgetc(read) ) != EOF ) {
if (c == ':' || c == '-') {
curl->desc = resolvell(head, &sz);
consumespaces(read);
}
switch (c) {
case ':':
curl = insorget(root->links, line(read));
cur = curl->to;
break;
case '-': ;
char* lname = line(read);
node* at = insorget(root->links, lname)->to;
curl = addbstlink(cur->links, lname, at);
break;
default:
ungetc(c, read);
case '.':
tail = appendll(tail, line(read));
sz += strlen(tail->str);
break;
}
}
fclose(read);
return root;
}
|