forked from teamhimeh/simutrans
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathfetchopt.h
96 lines (77 loc) · 2.8 KB
/
fetchopt.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
/* fetchopt.h
*
* Options parsing class
* May 2011
* by Timothy Baldock
*/
/*
This class can be used to parse unix-style single character
command line options. It is intended to provide a similar interface to
the POSIX getopt() function.
The constructor takes the number of arguments (typically the argc value),
the array of arguments and an options string describing the options that
should be searched for.
The value of the options string is constructed from the single-character
options flags you wish to search for. A colon ':' following the option
indicates that the option should take an argument. It is an error if an
option is indicated as having an argument and no argument is found.
E.g. the options string "a:bc" indicates that three flags should be
searched for: -a (which takes an argument), -b and -c (which do not).
The next() method will return the character representing the next option
found. When no further options are found it will return -1. If an error
condition is encountered the character '?' is returned.
The get_optarg() method returns the argument value of the current option
(or NULL if the current option does not take an argument).
When all option arguments have been parsed the value of get_optind()
will be the index into the argv array of the next non-option argument.
A return value of '?' indicates an error, program usage ought to be
printed if this is encountered.
Example:
// Parsing the following command line:
// mycommand -a override -bc somecommand
Fetchopt_t fetchopt(argc, argv, "a:bc");
const char default_arg_a[] = "default";
char *arg_a = default_arg_a;
bool flag_b = true;
bool flag_c = false;
int ch;
while ((ch = fetchopt.next()) != -1) {
switch (ch) {
case 'a':
arg_a = fetchopt.get_optarg();
break;
case 'b':
flag_b = false;
break;
case 'c':
flag_c = true;
break;
case '?':
case 'h':
default:
usage();
}
}
// Values will be:
// arg_a = "override"
// flag_b = false
// flag_c i = true
// fetchopt.get_optind() = 4
// argv[fetchopt.get_optind()] = "somecommand"
*/
#ifndef FETCHOPT_H
#define FETCHOPT_H
class Fetchopt_t {
const char *optstr; // Options definition string
int ac; // argc
char **av; // argv
char *optarg; // Current option's argument string
int optind; // Index of current option in argv
int pos; // Position of option within current argument
public:
Fetchopt_t(int, char **, const char *optstring);
char *get_optarg();
int get_optind();
int next();
};
#endif