-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathutil.c
108 lines (75 loc) · 1.54 KB
/
util.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
#include <ctype.h>
#include <limits.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
const char *make_tmpfile_template = "/tmp/tsql.XXXXXX.tsv";
const int make_tmpfile_suffix_length = 4;
char *
make_tmpfile() {
char buf[PATH_MAX];
strcpy(buf, make_tmpfile_template);
int fd = mkstemps(buf, make_tmpfile_suffix_length);
if (fd != -1) {
if (close(fd) == -1) {
perror("failed to close temp file");
return NULL;
}
return strdup(buf);
} else {
perror("mkstemp failed");
return NULL;
}
}
void
trim(char *s) {
char *first = s;
size_t i;
while (isspace(*first)) {
++first;
}
int lede = first - s;
if (lede) {
for (i = 0; *(s + lede + i); ++i) {
s[i] = s[lede + i];
}
s[i] = s[lede + i];
}
i = strlen(s) - 1;
while(i >= 0 && isspace(s[i])) {
--i;
}
s[i + 1] = '\0';
}
char **
split(char *s, char delim) {
char **parts;
int i;
if (strlen(s) == 0) {
parts = calloc(1, sizeof(char *));
return parts;
}
int delim_cnt = 0;
for (i = 0; s[i]; ++i) {
if (s[i] == delim) {
++delim_cnt;
}
}
parts = calloc(delim_cnt + 2, sizeof(char *));
char *lastp = s;
char *p;
i = 0;
while (p = index(lastp, delim)) {
parts[i] = (char *)calloc(p - lastp + 1, sizeof(char));
strncpy(parts[i], lastp, p - lastp);
lastp = p + 1;
++i;
}
parts[i] = (char *)calloc(strlen(lastp), sizeof(char));
strcpy(parts[i], lastp);
return parts;
}
void
free_split_array(char **split_array) {
/* implement me */
}