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 | |
| 18 | c = getopt (argc, argv, "abc:d:0123456789"); |
| 19 | if (c == EOF) |
| 20 | break; |
| 21 | |
| 22 | switch (c) |
| 23 | { |
| 24 | case '0': |
| 25 | case '1': |
| 26 | case '2': |
| 27 | case '3': |
| 28 | case '4': |
| 29 | case '5': |
| 30 | case '6': |
| 31 | case '7': |
| 32 | case '8': |
| 33 | case '9': |
| 34 | if (digit_optind != 0 && digit_optind != this_option_optind) |
| 35 | printf ("digits occur in two different argv-elements.\n"); |
| 36 | digit_optind = this_option_optind; |
| 37 | printf ("option %c\n", c); |
| 38 | break; |
| 39 | |
| 40 | case 'a': |
| 41 | printf ("option a\n"); |
| 42 | break; |
| 43 | |
| 44 | case 'b': |
| 45 | printf ("option b\n"); |
| 46 | break; |
| 47 | |
| 48 | case 'c': |
| 49 | printf ("option c with value `%s'\n", optarg); |
| 50 | break; |
| 51 | |
| 52 | case '?': |
| 53 | break; |
| 54 | |
| 55 | default: |
| 56 | printf ("?? getopt returned character code 0%o ??\n", c); |
| 57 | } |
| 58 | } |
| 59 | |
| 60 | if (optind < argc) |
| 61 | { |
| 62 | printf ("non-option ARGV-elements: "); |
| 63 | while (optind < argc) |
| 64 | printf ("%s ", argv[optind++]); |
| 65 | printf ("\n"); |
| 66 | } |
| 67 | exit (0); |
| 68 | } |
| 69 | |