File tests/src/test_getopt.c added (mode: 100644) (index 0000000..4b4a32e) |
|
1 |
|
/* |
|
2 |
|
============================================================================ |
|
3 |
|
Name : test_getopt.c |
|
4 |
|
Author : martin.dvorak@mindforger.com |
|
5 |
|
Copyright : Apache 2.0 |
|
6 |
|
Description : A test |
|
7 |
|
============================================================================ |
|
8 |
|
*/ |
|
9 |
|
|
|
10 |
|
#include <stdio.h> /* for printf */ |
|
11 |
|
#include <stdlib.h> /* for exit */ |
|
12 |
|
#include <getopt.h> |
|
13 |
|
|
|
14 |
|
int main(int argc, char **argv) |
|
15 |
|
{ |
|
16 |
|
int c; |
|
17 |
|
int digit_optind = 0; |
|
18 |
|
|
|
19 |
|
while (1) { |
|
20 |
|
int this_option_optind = optind ? optind : 1; |
|
21 |
|
int option_index = 0; |
|
22 |
|
static struct option long_options[] = { |
|
23 |
|
{"add", required_argument, 0, 0 }, |
|
24 |
|
{"append", no_argument, 0, 0 }, |
|
25 |
|
{"delete", required_argument, 0, 0 }, |
|
26 |
|
{"verbose", no_argument, 0, 0 }, |
|
27 |
|
{"create", required_argument, 0, 'c'}, |
|
28 |
|
{"file", required_argument, 0, 0 }, |
|
29 |
|
{0, 0, 0, 0 } |
|
30 |
|
}; |
|
31 |
|
|
|
32 |
|
c = getopt_long(argc, argv, "abc:d:012", long_options, &option_index); |
|
33 |
|
if (c == -1) |
|
34 |
|
break; |
|
35 |
|
|
|
36 |
|
|
|
37 |
|
switch (c) { |
|
38 |
|
case 0: |
|
39 |
|
printf("option %s", long_options[option_index].name); |
|
40 |
|
if (optarg) |
|
41 |
|
printf(" with arg %s", optarg); |
|
42 |
|
printf("\n"); |
|
43 |
|
break; |
|
44 |
|
|
|
45 |
|
case '0': |
|
46 |
|
case '1': |
|
47 |
|
case '2': |
|
48 |
|
if (digit_optind != 0 && digit_optind != this_option_optind) |
|
49 |
|
printf("digits occur in two different argv-elements.\n"); |
|
50 |
|
digit_optind = this_option_optind; |
|
51 |
|
printf("option %c\n", c); |
|
52 |
|
break; |
|
53 |
|
|
|
54 |
|
case 'a': |
|
55 |
|
printf("option a\n"); |
|
56 |
|
break; |
|
57 |
|
|
|
58 |
|
case 'b': |
|
59 |
|
printf("option b\n"); |
|
60 |
|
break; |
|
61 |
|
|
|
62 |
|
case 'c': |
|
63 |
|
printf("option c with value '%s'\n", optarg); |
|
64 |
|
break; |
|
65 |
|
|
|
66 |
|
case 'd': |
|
67 |
|
printf("option d with value '%s'\n", optarg); |
|
68 |
|
break; |
|
69 |
|
|
|
70 |
|
case '?': |
|
71 |
|
|
|
72 |
|
break; |
|
73 |
|
|
|
74 |
|
default: |
|
75 |
|
printf("?? getopt returned character code 0%o ??\n", c); |
|
76 |
|
} |
|
77 |
|
} |
|
78 |
|
|
|
79 |
|
if (optind < argc) { |
|
80 |
|
printf("non-option ARGV-elements: "); |
|
81 |
|
while (optind < argc) |
|
82 |
|
printf("%s ", argv[optind++]); |
|
83 |
|
printf("\n"); |
|
84 |
|
} |
|
85 |
|
|
|
86 |
|
exit(EXIT_SUCCESS); |
|
87 |
|
} |