-
Notifications
You must be signed in to change notification settings - Fork 0
/
pickopt.c
52 lines (47 loc) · 1.23 KB
/
pickopt.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
#include <string.h>
#include <stdbool.h>
// @c pointer to original argc
// @v pointer to original argv
// @o option name (after hyphen)
// @d default value
const char * pick_option(int *c, char ***v, const char *o, const char *d)
{
int argc = *c;
char **argv = *v;
int id = d ? 1 : 0;
for (int i = 0; i < argc - id; i++)
if (argv[i][0] == '-' && 0 == strcmp(argv[i]+1, o))
{
char *r = argv[i+id]+1-id;
*c -= id+1;
for (int j = i; j < argc - id; j++)
(*v)[j] = (*v)[j+id+1];
return r;
}
return d;
}
// char *oval = pick_option(&argc, &argv, "o", "37");
// returns "37" or the value of the option, removes 0 or 2 arguments
//
// bool o = pick_option(&argc, &argv, "o", NULL);
// returns NULL or true, removes 0 or 1 arguments
//
#ifdef MAIN_PICKOPT
#include <stdio.h>
static void print_args(int c, char **v)
{
for (int i = 0; i <= c; i++)
printf("ARG[%d/%d] = \"%s\"\n", i, c, v[i]);
}
int main(int c, char **v)
{
printf("arguments before processing:\n");
print_args(c, v);
// char *o = pick_option(&c, &v, "o", "42");
// printf("o = \"%s\"\n", o);
printf("pick_option 'o' is: \"%d\"\n", (bool) pick_option(&c, &v, "o", NULL));
printf("arguments after processing:\n");
print_args(c, v);
return 0;
}
#endif//MAIN_PICKOPT