Repository navigation
Expand file tree
/
Copy pathgetopt_flags.c
More file actions
71 lines (62 loc) · 1.69 KB
/
Copy pathgetopt_flags.c
File metadata and controls
71 lines (62 loc) · 1.69 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
/*
* Example program demonstrating getopt() usage.
*
* Parses command-line options using getopt(). Exactly one option must be
* specified, followed by a single non-option argument.
*
* Demonstrates option parsing, error handling, and use of optind.
*/
#include <getopt.h>
#include <stdio.h>
int main(int argc, char *argv[])
{
char *prog = argv[0];
/* Allowable argument options. */
char *options = "abc";
/* Optionally turn off getopt built in error reporting */
opterr = 0;
/* Check that provided option is valid. */
char selection = 0;
int selected = 0;
int opt;
while ((opt = getopt(argc, argv, options)) != -1)
{
switch (opt)
{
case 'a':
selected++;
selection = opt;
break;
case 'b':
selected++;
selection = opt;
break;
case 'c':
selected++;
selection = opt;
break;
default: /* '?' */
fprintf(stderr, "%s: invalid option: -%c\n", prog, optopt);
return 1;
}
}
/* Ensure that only one option was selected. */
if (selected != 1)
{
fprintf(stderr, "%s: one option must be selected.\n", prog);
return 1;
}
/*
* Ensure proper usage; in this case one option and one non-option arg following.
* optind is the index in argv of the first argv-element that is not an option.
*/
if (argc != optind + 1)
{
fprintf(stderr, "Usage: %s (-a | -b | -c) arg\n", prog);
return 1;
}
/* All checks passed; print results. */
printf("Option: %c\n", selection);
printf("Arg: %s\n", argv[optind]);
return 0;
}