This repository has been archived by the owner on Jan 6, 2020. It is now read-only.
forked from cavaliercoder/sysinv
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathargparser.cpp
71 lines (59 loc) · 1.54 KB
/
argparser.cpp
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
#include "stdafx.h"
#include "argparser.h"
#include <stdlib.h>
int arg_is_switch(char *arg);
PARGLIST parse_args(int argc, char* argv[])
{
char *c = NULL;
char *val = NULL;
char *cursor = NULL;
PARGLIST argList = (PARGLIST) calloc(1, 1024);
int bufferlen = 0;
int arg = 0;
int i = 0;
// Set pointer of arguments to memory following arglist
if(argc > 0)
argList->args = (PARG)(argList + 1);
// First count switchs
for(i = 0; i < argc; i++)
if(arg_is_switch(argv[i]))
argList->count++;
// Move memory cursor to end of last arg structure
cursor = (char *) &argList->args[argList->count];
// Parse
arg = 0;
for(i = 0; i < argc; i++) {
if(arg_is_switch(argv[i])) {
argList->args[arg].arg = cursor;
// Copy until we find a '=' or ':'
for(c = &argv[i][0]; *c != ':' && *c != '=' && *c != '\0'; c++) {
(* cursor++) = *c;
}
(*cursor++) = '\0';
// Copy value from this switch or the next arg?
val = NULL;
if(*c == ':' || *c == '=') {
val = c + 1;
}
else {
if(((i + 1) < argc) && (0 == arg_is_switch(argv[i + 1])))
val = argv[i + 1];
}
// Copy value
if(NULL != val) {
argList->args[arg].val = cursor;
strcpy(argList->args[arg].val, val);
cursor += strlen(argList->args[arg].val);
(*cursor++) = '\0';
}
arg++;
}
}
bufferlen = cursor - (char *) argList;
argList = (PARGLIST) realloc(argList, bufferlen);
return argList;
}
int arg_is_switch(char *arg)
{
return (arg[0] == '/' || arg[0] == '-');
}