-
Notifications
You must be signed in to change notification settings - Fork 0
/
getopt_demo.c
53 lines (47 loc) · 1.25 KB
/
getopt_demo.c
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
#include <getopt.h>
#include <stdio.h>
#include <stdlib.h>
int main(int argc, char *argv[])
{
while (1)
{
int opt;
// Follow an argument with a colon to require an argument
// The argument will be placed in optarg
opt = getopt(argc, argv, "ab:c");
if (opt == -1)
{
break;
}
switch (opt)
{
case 'a':
printf("Option 'a'\n");
break;
case 'b':
printf("Option 'b': %s\n", optarg);
break;
case 'c':
printf("Option 'c'\n");
break;
case '?': // Unrecognized option
case ':': // Missing argument
default:
fprintf(stderr, "Usage: %s [-ac] [-b val] [ARG]\n", argv[0]);
exit(EXIT_FAILURE);
}
}
// Adjust this logic if multiple positional arguments are required
if (optind >= argc)
{
fprintf(stderr, "Expected argument after options\n");
fprintf(stderr, "Usage: %s [-ac] [-b val]\n", argv[0]);
exit(EXIT_FAILURE);
}
do
{
printf("%s ", argv[optind++]);
} while (optind < argc);
printf("\n");
return 0;
}