yuezonghe | 824eb0c | 2024-06-27 02:32:26 -0700 | [diff] [blame^] | 1 | /* Getopt tests */ |
| 2 | |
| 3 | #include <stdio.h> |
| 4 | #include <string.h> |
| 5 | #include <stdlib.h> |
| 6 | #include <getopt.h> |
| 7 | |
| 8 | |
| 9 | int main (int argc, char **argv) |
| 10 | { |
| 11 | int c; |
| 12 | int digit_optind = 0; |
| 13 | |
| 14 | while (1) |
| 15 | { |
| 16 | int this_option_optind = optind ? optind : 1; |
| 17 | int option_index = 0; |
| 18 | static struct option long_options[] = |
| 19 | { |
| 20 | {"add", 1, 0, 0}, |
| 21 | {"append", 0, 0, 0}, |
| 22 | {"delete", 1, 0, 0}, |
| 23 | {"verbose", 0, 0, 0}, |
| 24 | {"create", 0, 0, 0}, |
| 25 | {"file", 1, 0, 0}, |
| 26 | {0, 0, 0, 0} |
| 27 | }; |
| 28 | |
| 29 | c = getopt_long (argc, argv, "abc:d:0123456789", |
| 30 | long_options, &option_index); |
| 31 | if (c == EOF) |
| 32 | break; |
| 33 | |
| 34 | switch (c) |
| 35 | { |
| 36 | case 0: |
| 37 | printf ("option %s", long_options[option_index].name); |
| 38 | if (optarg) |
| 39 | printf (" with arg %s", optarg); |
| 40 | printf ("\n"); |
| 41 | break; |
| 42 | |
| 43 | case '0': |
| 44 | case '1': |
| 45 | case '2': |
| 46 | case '3': |
| 47 | case '4': |
| 48 | case '5': |
| 49 | case '6': |
| 50 | case '7': |
| 51 | case '8': |
| 52 | case '9': |
| 53 | if (digit_optind != 0 && digit_optind != this_option_optind) |
| 54 | printf ("digits occur in two different argv-elements.\n"); |
| 55 | digit_optind = this_option_optind; |
| 56 | printf ("option %c\n", c); |
| 57 | break; |
| 58 | |
| 59 | case 'a': |
| 60 | printf ("option a\n"); |
| 61 | break; |
| 62 | |
| 63 | case 'b': |
| 64 | printf ("option b\n"); |
| 65 | break; |
| 66 | |
| 67 | case 'c': |
| 68 | printf ("option c with value `%s'\n", optarg); |
| 69 | break; |
| 70 | |
| 71 | case 'd': |
| 72 | printf ("option d with value `%s'\n", optarg); |
| 73 | break; |
| 74 | |
| 75 | case '?': |
| 76 | break; |
| 77 | |
| 78 | default: |
| 79 | printf ("?? getopt returned character code 0%o ??\n", c); |
| 80 | } |
| 81 | } |
| 82 | |
| 83 | if (optind < argc) |
| 84 | { |
| 85 | printf ("non-option ARGV-elements: "); |
| 86 | while (optind < argc) |
| 87 | printf ("%s ", argv[optind++]); |
| 88 | printf ("\n"); |
| 89 | } |
| 90 | |
| 91 | exit (0); |
| 92 | } |
| 93 | |