-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathstreamtokenizer.c
More file actions
91 lines (75 loc) · 2.21 KB
/
streamtokenizer.c
File metadata and controls
91 lines (75 loc) · 2.21 KB
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
#include "streamtokenizer.h"
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <ctype.h>
#include <assert.h>
void STNew(streamtokenizer *st, FILE *infile, const char *delimiters, bool discardDelimiters)
{
assert(infile != NULL);
assert(delimiters != NULL);
assert(strlen(delimiters) > 0);
st->infile = infile;
st->discardDelimiters = discardDelimiters;
st->delimiters = strdup(delimiters);
}
void STDispose(streamtokenizer *st)
{
free((void *) st->delimiters); // donates the memory allocated by strdup back to the heap
}
bool STNextToken(streamtokenizer *st, char buffer[], int bufferLength)
{
return STNextTokenUsingDifferentDelimiters(st, buffer, bufferLength, st->delimiters);
}
bool STNextTokenUsingDifferentDelimiters(streamtokenizer *st, char buffer[], int bufferLength, const char *delimiters)
{
int i;
int next;
assert(buffer != NULL);
assert(bufferLength >= 2);
if (st->discardDelimiters) STSkipOver(st, delimiters);
next = getc(st->infile);
if (next == EOF) return false;
buffer[0] = next;
if (strchr(delimiters, next) != NULL) {
buffer[1] = '\0';
return true;
}
// pull characters until hit stop character, or until buffer is full
for (i = 1; i < bufferLength - 1; i++) { // leave room for '\0'
next = fgetc(st->infile);
if (next == EOF) break;
if (strchr(delimiters, next) != NULL) {
ungetc(next, st->infile);
break;
}
buffer[i] = next;
}
// i indexes place where null-term should be placed...
buffer[i] = '\0';
return true;
}
static bool HaveReasonToStop(const char *charSet, int next, bool skipping)
{
bool inSet = (strchr(charSet, next) != NULL);
return ((inSet && !skipping) || (!inSet && skipping));
}
static int STSkipHelper(streamtokenizer *st, const char *charSet, bool skipping)
{
int next;
while (true) {
next = getc(st->infile);
if (next == EOF) return EOF;
if (HaveReasonToStop(charSet, next, skipping)) break;
}
ungetc(next, st->infile);
return next;
}
int STSkipUntil(streamtokenizer *st, const char *skipUntilSet)
{
return STSkipHelper(st, skipUntilSet, false);
}
int STSkipOver(streamtokenizer *st, const char *skipSet)
{
return STSkipHelper(st, skipSet, true);
}