-
Notifications
You must be signed in to change notification settings - Fork 1
/
CSV.c
112 lines (92 loc) · 2.45 KB
/
CSV.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 "CSV.h"
#include "File.h"
#include <string.h> /* strchr */
#include <stdio.h> /* fprintf */
String *CSV_get(CSV_table *csv, int row, int column)
{
if (row > csv->_rows-1) {
return NULL;
}
if (column > csv->_columns-1) {
return NULL;
}
int i = (row * csv->_columns) + column;
return csv->_entries.items[i];
}
CSV_table *CSV_load(String *path)
{
if (!path) {
return NULL;
}
String *contents = File_load_text(path);
if (!contents) {
return NULL;
}
CSV_table *csv = Mem_calloc(1, sizeof(*csv));
char *p = contents->bytes;
char *newline;
char *comma;
int columns = 0;
int rows = 0;
while (1) {
//puts("-------");
int ccount = 0;
newline = strchr(p, '\n');
if (!newline) {
break;
}
*newline = 0;
while (p < newline) {
ccount += 1;
comma = strchr(p, ',');
if (!comma) {
comma = newline; /* allow trailing comma or newline to end a row */
}
int len = comma - p + 1; /* leave room to null-terminate tmp */
char tmp[len];
strncpy(tmp, p, len); /* does not copy the comma */
tmp[len-1] = 0; /* null-terminate */
//printf("%s\n", tmp);
#if 1
IndexedSet_add(csv->_entries, String_new(tmp));
#else
{
if (csv->_entries.items == 0L) {
printf("%d\n", __LINE__);
csv->_entries.avail = 2;
printf("%d\n", __LINE__);
csv->_entries.items = _Mem_calloc(csv->_entries.avail, sizeof(String_new(tmp)), __func__);
printf("%d\n", __LINE__);
}
else if (csv->_entries.avail == csv->_entries.count) {
printf("%d\n", __LINE__);
csv->_entries.avail *= 2;
printf("%d\n", __LINE__);
csv->_entries.items = _Mem_realloc(csv->_entries.items, csv->_entries.avail * sizeof(String_new(tmp)), __func__);
printf("%d\n", __LINE__);
}
printf("%d\n", __LINE__);
csv->_entries.items[csv->_entries.count] = String_new(tmp);
printf("%d\n", __LINE__);
csv->_entries.count += 1;
printf("%d\n", __LINE__);
}
#endif
p = comma + 1;
}
if (columns == 0) {
columns = ccount;
}
if (columns != ccount) {
fprintf(stderr, "found %d columns, expected %d!\n", columns, ccount);
return NULL;
}
rows += 1;
if (*p == 0) {
break;
}
}
csv->_rows = rows;
csv->_columns = columns;
return csv;
}