-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathcmdline.cpp
More file actions
108 lines (87 loc) · 2.17 KB
/
Copy pathcmdline.cpp
File metadata and controls
108 lines (87 loc) · 2.17 KB
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
#include <iostream>
#include <string>
#include <cstdlib>
#include "cmdline.h"
using namespace std;
cmdline::cmdline(){
}
cmdline::cmdline(option_t *table) : option_table(table) {
}
void cmdline::parse(int argc, char * const argv[]) {
#define END_OF_OPTIONS(p) \
((p)->short_name == 0 \
&& (p)->long_name == 0 \
&& (p)->parse == 0)
for (option_t *op = option_table; !END_OF_OPTIONS(op); ++op)
op->flags &= ~OPT_SEEN;
for (int i = 1; i < argc; ++i) {
if (argv[i][0] != '-') {
cerr << "Invalid non-option argument: " << argv[i] << endl;
exit(1);
}
if (argv[i][1] == '-' && argv[i][2] == 0)
break;
if (argv[i][1] == '-')
i += do_long_opt(&argv[i][2], argv[i + 1]);
else
i += do_short_opt(&argv[i][1], argv[i + 1]);
}
for (option_t *op = option_table; !END_OF_OPTIONS(op); ++op) {
#define OPTION_NAME(op) \
(op->short_name ? op->short_name : op->long_name)
if (op->flags & OPT_SEEN)
continue;
if (op->flags & OPT_MANDATORY) {
cerr << "Option " << "-" << OPTION_NAME(op) << " is mandatory." << "\n";
exit(1);
}
if (op->def_value == 0)
continue;
op->parse(string(op->def_value));
}
}
int cmdline::do_long_opt(const char *opt, const char *arg) {
for (option_t *op = option_table; op->long_name != 0; ++op) {
if (string(opt) == string(op->long_name)) {
op->flags |= OPT_SEEN;
if (op->has_arg) {
if (arg == 0) {
cerr << "Option requires argument: " << "--" << opt << "\n";
exit(1);
}
op->parse(string(arg));
return 1;
}
else {
op->parse(string(""));
return 0;
}
}
}
cerr << "Unknown option: " << "--" << opt << "." << endl;
exit(1);
return -1;
}
int cmdline::do_short_opt(const char *opt, const char *arg) {
option_t *op;
for (op = option_table; op->short_name != 0; ++op) {
if (string(opt) == string(op->short_name)) {
op->flags |= OPT_SEEN;
if (op->has_arg) {
if (arg == 0) {
cerr << "Option requires argument: " << "-" << opt << "\n";
exit(1);
}
op->parse(string(arg));
return 1;
}
else {
op->parse(string(""));
return 0;
}
}
}
cerr << "Unknown option: " << "-" << opt << "." << endl;
exit(1);
return -1;
}