-
Notifications
You must be signed in to change notification settings - Fork 1
/
csv_helpers.h
98 lines (93 loc) · 2.3 KB
/
csv_helpers.h
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
//csvReadText() and csvReadInt() are from the SdFat example "readCsv.ino" Copyright (c) 2011-2018 Bill Greiman under MIT license
//All other code is based on the same example
#ifndef CSV_HELPERS_h
#define CSV_HELPERS_h
/*
* Read a file one field at a time.
*
* file - File to read.
*
* str - Character array for the field.
*
* size - Size of str array.
*
* delim - csv delimiter.
*
* return - negative value for failure.
* delimiter, '\n' or zero(EOF) for success.
*/
int csvReadText(File* file, char* str, size_t size, char delim) {
char ch;
int rtn;
size_t n = 0;
while (true) {
// check for EOF
if (!file->available()) {
rtn = 0;
break;
}
if (file->read(&ch, 1) != 1) {
// read error
rtn = -1;
break;
}
// Delete CR.
if (ch == '\r') {
continue;
}
if (ch == delim || ch == '\n') {
rtn = ch;
break;
}
if ((n + 1) >= size) {
// string too long
rtn = -2;
n--;
break;
}
str[n++] = ch;
}
str[n] = '\0';
return rtn;
}
int csvReadInt(File* file, int* num, char delim) {
char buf[20];
char* ptr;
int rtn = csvReadText(file, buf, sizeof(buf), delim);
if (rtn < 0) return rtn;
*num = strtol(buf, &ptr, 10);
if (buf == ptr) return -3;
while(isspace(*ptr)) ptr++;
return *ptr == 0 ? rtn : -4;
}
int csvReadBool(File* file, bool* boolptr, char delim) {
char buf[20];
char* ptr;
int rtn = csvReadText(file, buf, sizeof(buf), delim);
if (rtn < 0) return rtn;
*boolptr = strtol(buf, &ptr, 10) == 1 ? true : false;
if (buf == ptr) return -3;
while(isspace(*ptr)) ptr++;
return *ptr == 0 ? rtn : -4;
}
int csvReadPBType(File* file, PlaybackType* type, char delim) {
char buf[20];
char* ptr;
int rtn = csvReadText(file, buf, sizeof(buf), delim);
if (rtn < 0) return rtn;
*type = (PlaybackType)strtol(buf, &ptr, 10);
if (buf == ptr) return -3;
while(isspace(*ptr)) ptr++;
return *ptr == 0 ? rtn : -4;
}
int csvReadPBState(File* file, PlaybackState* state, char delim) {
char buf[20];
char* ptr;
int rtn = csvReadText(file, buf, sizeof(buf), delim);
if (rtn < 0) return rtn;
*state = (PlaybackState)strtol(buf, &ptr, 10);
if (buf == ptr) return -3;
while(isspace(*ptr)) ptr++;
return *ptr == 0 ? rtn : -4;
}
#endif //CSV_HELPERS_h