-
Notifications
You must be signed in to change notification settings - Fork 8
Expand file tree
/
Copy pathstringv.c
More file actions
141 lines (107 loc) · 2.37 KB
/
Copy pathstringv.c
File metadata and controls
141 lines (107 loc) · 2.37 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
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
140
141
#define _POSIX_C_SOURCE 200809L // for getline
#include <ctype.h>
#include <stdarg.h>
#include <stddef.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include "strings.h"
char*
strdup_printf(char *fmt, ...)
{
char *ret_str = NULL;
va_list ap;
int bytes_to_allocate;
va_start(ap, fmt);
bytes_to_allocate = vsnprintf(ret_str, 0, fmt, ap);
va_end(ap);
// Add one for '\0'
bytes_to_allocate++;
ret_str = (char *)malloc(bytes_to_allocate * sizeof(char));
if (ret_str == NULL) {
fprintf(stderr, "failed to allocate memory\n");
return NULL;
}
va_start(ap, fmt);
bytes_to_allocate = vsnprintf(ret_str, bytes_to_allocate, fmt, ap);
va_end(ap);
return ret_str;
}
char**
strsplitv(char *string, char *delim)
{
char **array;
char *pos;
char *start;
int i = 0;
unsigned int delim_len;
if(string == NULL) return NULL;
if(delim == NULL) return NULL;
delim_len = strlen(delim);
if(strlen(string) < delim_len) return NULL;
pos = string;
do
{
pos = strstr(pos, delim);
if(pos != NULL)
{
pos += delim_len;
i++;
}
}
while(pos != NULL);
array = (char**)calloc(i + 2, sizeof(char*));
i = 0;
start = string;
do
{
pos = strstr(start, delim);
if(pos != NULL)
{
array[i] = strndup(start, (pos - start));
start = pos;
start += delim_len;
i++;
}
}
while(pos != NULL);
if(array[i] == NULL) array[i] = strdup(start);
return array;
}
char**
strdupv(char **array, int limit)
{
int i = 0;
char **retval;
if(array == NULL) return NULL;
// how many items are there?
while(array[i]) i++;
// alloc first dimension
retval = (char**)calloc(i + 1, sizeof(char*));
i = 0;
while(array[i])
{
retval[i] = strdup(array[i]);
i++;
if(limit > 0)
{
if((i - 1) == limit) break;
}
}
return retval;
}
void
strfreev(char **array)
{
char **rewind = NULL;
if(array == NULL) return;
rewind = array;
while(*array != NULL)
{
free(*array);
array++;
}
free(rewind);
return;
}