-
Notifications
You must be signed in to change notification settings - Fork 17
/
argv.h
131 lines (117 loc) · 2.74 KB
/
argv.h
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
#ifndef ARGV_H
#define ARGV_H
static char* decode_string(char* str)
{
size_t str_len = strlen(str), i = 0;
char* dest = str;
if ((str_len > 1) && ((*str == '\"') || (*str == '\'')) && (str[str_len - 1] == *str)) {
memmove(str, str + 1, str_len - 2);
str[str_len - 2] = 0;
}
while (*str) {
if (*str == '\\') {
str++;
}
dest[i++] = *str++;
}
dest[i] = 0;
return (dest);
}
static char* find_next_match(char* str, char match_char)
{
char* pos = 0;
while (*str) {
if (*str == match_char) {
pos = str;
break;
}
if (*str == '\\') {
if (str[1]) {
str++;
} else {
break;
}
}
str++;
}
return (pos);
}
static char* get_param(char* str)
{
static char* pos = 0;
char* token = 0;
if (str) // Start a new string?
{
pos = str;
}
if (pos) {
// Skip delimiters
while (*pos == ' ') {
pos++;
}
if (*pos) {
token = pos;
// Skip non-delimiters
while (*pos && (*pos != ' ')) {
// Skip quoted characters
if ((*pos == '\"') || (*pos == '\'')) {
char* match_pos = 0;
if ((match_pos = find_next_match(pos + 1, *pos))) {
pos = match_pos;
}
}
// Skip escaped spaces
if (*pos == '\\') {
pos++;
}
pos++;
}
if (*pos) {
*pos++ = '\0';
}
}
}
return (token);
}
static size_t count_param(char* str)
{
size_t i = 0;
while (*str) {
// Skip delimiters
while (*str == ' ') {
str++;
}
// Skip non-delimiters
while (*str && (*str != ' ')) {
// Skip quoted characters
if ((*str == '\"') || (*str == '\'')) {
char* match_str = 0;
if ((match_str = find_next_match(str + 1, *str))) {
str = match_str;
}
}
// Skip escaped spaces
if (*str == '\\') {
str++;
}
str++;
}
i++;
}
return (i);
}
static char** build_argv(char* str)
{
size_t argc = count_param(str);
char** argv = (char**)malloc(sizeof(char*) * (argc + 1));
if (argv) {
char *p, **argp = argv;
for (p = get_param(str); p; p = get_param(0), argp++) {
*argp = decode_string(p);
}
*argp = 0;
return (argv);
}
return (0);
}
#endif