-
Notifications
You must be signed in to change notification settings - Fork 38
/
csv.c
139 lines (112 loc) · 2.74 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
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
#include <stdlib.h>
#include <string.h>
void free_csv_line( char **parsed ) {
char **ptr;
for ( ptr = parsed; *ptr; ptr++ ) {
free( *ptr );
}
free( parsed );
}
static int count_fields( const char *line ) {
const char *ptr;
int cnt, fQuote;
for ( cnt = 1, fQuote = 0, ptr = line; *ptr; ptr++ ) {
if ( fQuote ) {
if ( *ptr == '\"' ) {
fQuote = 0;
}
continue;
}
switch( *ptr ) {
case '\"':
fQuote = 1;
continue;
case ',':
cnt++;
continue;
default:
continue;
}
}
if ( fQuote ) {
return -1;
}
return cnt;
}
/*
* Given a string containing no linebreaks, or containing line breaks
* which are escaped by "double quotes", extract a NULL-terminated
* array of strings, one for every cell in the row.
*/
char **parse_csv( const char *line ) {
char **buf, **bptr, *tmp, *tptr;
const char *ptr;
int fieldcnt, fQuote, fEnd;
fieldcnt = count_fields( line );
if ( fieldcnt == -1 ) {
return NULL;
}
buf = malloc( sizeof(char*) * (fieldcnt+1) );
if ( !buf ) {
return NULL;
}
tmp = malloc( strlen(line) + 1 );
if ( !tmp ) {
free( buf );
return NULL;
}
bptr = buf;
for ( ptr = line, fQuote = 0, *tmp = '\0', tptr = tmp, fEnd = 0; ; ptr++ ) {
if ( fQuote ) {
if ( !*ptr ) {
break;
}
if ( *ptr == '\"' ) {
if ( ptr[1] == '\"' ) {
*tptr++ = '\"';
ptr++;
continue;
}
fQuote = 0;
}
else {
*tptr++ = *ptr;
}
continue;
}
switch( *ptr ) {
case '\"':
fQuote = 1;
continue;
case '\0':
fEnd = 1;
case ',':
*tptr = '\0';
*bptr = strdup( tmp );
if ( !*bptr ) {
for ( bptr--; bptr >= buf; bptr-- ) {
free( *bptr );
}
free( buf );
free( tmp );
return NULL;
}
bptr++;
tptr = tmp;
if ( fEnd ) {
break;
} else {
continue;
}
default:
*tptr++ = *ptr;
continue;
}
if ( fEnd ) {
break;
}
}
*bptr = NULL;
free( tmp );
return buf;
}