-
Notifications
You must be signed in to change notification settings - Fork 1
/
arg_parse.c
85 lines (72 loc) · 1.53 KB
/
arg_parse.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
#include "arg_parse.h"
/* this file contains all of the argument parsing funtions that are used
* to interpret the user input. */
int get_argc(char *s)
{
char *sp = s;
int count = 0;
while (*sp != '\0') {
while (isspace(*sp) && *sp != '\0')
sp++;
if (*sp == '\0')
return count;
else
count++;
while (!isspace(*sp) && *sp != '\0')
sp++;
}
return count;
}
char *skip_flag(char *s)
{
while (!isspace(*s) && *s != '\0')
s++;
return s;
}
char **get_args(char *s, int index)
{
char **args, arg[BUFSIZE], *argp;
int i;
args = (char **) malloc (BUFSIZE);
s += index;
_argc = get_argc(s);
for (i = 0; i < _argc; i++) {
argp = arg;
top:
while (isspace(*s))
s++;
if (*s == '-') {
s = skip_flag(s);
_argc--;
goto top;
}
while (!isspace(*s) && *s != '\0')
*argp++ = *s++;
*argp = '\0';
args[i] = strdup(arg);
}
return args;
}
char *get_flags(char *buf)
{
char* flags = (char *) malloc(BUFSIZE);
while (*buf != '\0') {
if (*buf == '-') {
buf++;
while (!isspace(*buf) && *buf != '\0')
*flags++ = *buf++;
}
buf++;
}
*flags = '\0';
return flags;
}
void free_args(char **args) {
for (int i = 0; i < _argc; i++) {
free(args[i]);
}
free(args);
}
void free_flags(char *flags) {
free(flags);
}