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 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139
| #include <getopt.h> #include <stdio.h> #include <stdlib.h>
#define NO_LETTER (1) #define INVALID_VALUE (0xFFFFFFFF)
typedef enum { reqargIndex = 0, optargIndex, noargIndex, noletterIndex, nullIndex } option_index_t;
const struct option long_options[] = { {"reqarg", required_argument,NULL, 'r'}, {"optarg", optional_argument,NULL, 'o'}, {"noarg", no_argument, NULL,'n'}, {"noletter", no_argument, NULL, NO_LETTER }, {NULL, 0, NULL, NO_LETTER}, };
int a_val = INVALID_VALUE; int b_val = INVALID_VALUE; int c_val = INVALID_VALUE; int d_val = INVALID_VALUE; int r_val = INVALID_VALUE; int o_val = INVALID_VALUE; int n_val = INVALID_VALUE; int no_letter = INVALID_VALUE;
int setOption(int opt, char *optarg, char *argv[], int option_index) { switch(opt) { case 'a': if (optarg) { a_val = atoi(optarg); } else { a_val = 1; } break; case 'b': { b_val = atoi(optarg); } break; case 'c': c_val = atoi(optarg); break; case 'd': d_val = 1; if (optarg) { printf("warnning:option d no require argument. ignore value %s\n", optarg); } break; case 'r': { r_val = atoi(optarg); } break; case 'o': if (optarg) { o_val = atoi(optarg); } else { o_val = 1; } break; case 'n‘: n_val = 1; if (optarg) { printf("warnning:option n no require argument. ignore value %s\n", optarg); } break; case NO_LETTER: { switch(option_index) { case noletterIndex: no_letter = 1; break; case nullIndex:
break; default: break; } } break; default:
return 1; }
return 0; }
#define showV(x) printf(#x"=%d\n", x)
void showValues() { printf("=========\n"); showV(a_val); showV(b_val); showV(c_val); showV(d_val); showV(r_val); showV(o_val); showV(n_val); showV(no_letter); printf("=========\n");
}
int main(int argc, char *argv[]) { int opt; int option_index = 0; char *string = "a::b:c:dr:o::n"; //initValues(); while((opt =getopt_long_only(argc,argv,string,long_options,&option_index))!= -1) { printf("opt = %c\t\t", opt); printf("optarg = %s\t\t",optarg); printf("optind = %d\t\t",optind); printf("argv[optind] =%s\t\t", argv[optind]); printf("option_index = %d\n",option_index);
if (setOption(opt, optarg, argv, option_index)) { showValues(); return -1; } }
showValues();
return 0; }
|