- Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathutil.c
More file actions
Latest commit
113 lines (94 loc) · 2.22 KB
/
Copy pathutil.c
File metadata and controls
113 lines (94 loc) · 2.22 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
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
#include"util.h"
#include<assert.h>
#include<ctype.h>
//returns index of first occurance of c or -1 or c is not in string
intfind_first(constchar*line, charc) {
inti;
for(i=0; line[i]; ++i) {
if(line[i] ==c) {
returni;
}
}
return-1;
}
//replaces trailing newline (CRLF or LF) with null terminator
voidremove_endline(char*line, size_tlen) {
//there should actually be a endline
assert(line[len] =='\0'&&line[len-1] =='\n');
if(len>1&&line[len-2] =='\r') {
//CRLF
line[len-2] ='\0';
} else {
//LF
line[len-1] ='\0';
}
}
intis_trailing_space(charc) {
returnc=='\n'||c=='\r'||c==' '||c=='\t'||c=='\0';
}
//remove trailing whitespace (ie: ' ' \t \r \n)
voidremove_trailing_whitespace(char*line, size_tlen) {
inti= ((int)len) -1;
while(i >= 0&&is_trailing_space(line[i])) {
line[i--] ='\0';
}
}
char*strip(char*line) {
assert(line);
char*pos;
//skip leading whitespace
while(isspace(*line)) ++line;
pos=line;
//find end of string
while(*pos) ++pos;
//strip trailing whitespace
while(pos>line&& (isspace(*pos) ||*pos=='\0')) {
*pos--='\0';
}
returnline;
}
//parses unsigned decimal number, returns -1 on invalid digit string
intparse_uint(constchar*num_str) {
inti=0;
//empty string is invalid
do {
//non-digit found
if(!isdigit(*num_str)) {
return-1;
}
i=10*i+ (*num_str-'0');
++num_str;
} while(*num_str);
returni;
}
intparse_list(char*list, int (*handle_elt)(char*elt, void*args), void*args) {
assert(list);
assert(handle_elt);
intnum_elts=0;
intlen;
char*cur=list, *next=NULL;
//for each element of list
do {
//find end of element
len=find_first(cur, ',');
//null terminate element and save location of next
if(len >= 0) {
cur[len] ='\0';
next=cur+len+1;
}
//remove leading and trailing whitespace
cur=strip(cur);
//empty element
if(!cur[0]) {
//if whole list is empty, then this is ok
if(num_elts==0&& !next) return0;
//otherwise there is empty element or trailing ','
//ex: "abc, , efg" or "a, b, "
return-1;
}
if(handle_elt(cur, args) ==-1) return-1;
cur=next;
++num_elts;
} while(len!=-1);
returnnum_elts;
}