-
Notifications
You must be signed in to change notification settings - Fork 17
/
using_getopt.cpp
54 lines (48 loc) · 1.31 KB
/
using_getopt.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
// adapted from
// https://www.gnu.org/software/libc/manual/html_node/Example-of-Getopt.html
#include <iostream>
#include <unistd.h>
/// main() must be declared with arguments
/// otherwise command line arguments are ignored
int main(int argc, char **argv) {
bool aflag = 0;
bool bflag = 0;
std::string cvalue;
int cint_value;
int index;
int c;
opterr = 0;
// expected options are '-a', '-b', and '-c value'
while ((c = getopt(argc, argv, "abc:")) != -1)
switch (c) {
case 'a':
aflag = true;
break;
case 'b':
bflag = true;
break;
case 'c':
cvalue = optarg;
cint_value = atoi(cvalue.c_str());
break;
case '?':
if (optopt == 'c')
std::cerr << "Error: option -" << optopt << " requires an argument."
<< std::endl;
else
std::cerr << "Error: unknown option: " << optopt << std::endl;
return 1;
default:
return 0;
}
std::cout << "aflag=" << aflag << " "
<< "bflag=" << bflag << " "
<< "cvalue=" << cvalue << " "
<< "cint_value=" << cint_value << std::endl;
if (optind < argc) {
std::cout << "Found positional arguments\n";
for (index = optind; index < argc; index++)
std::cout << "Non-option argument: " << argv[index] << "\n";
}
return 0;
}