getopt.c 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420
  1. /* =============================================================================
  2. * PROGRAM: ularn
  3. * FILENAME: getopt.c
  4. *
  5. * DESCRIPTION:
  6. * Command line options processing functions.
  7. *
  8. * =============================================================================
  9. * EXPORTED VARIABLES
  10. *
  11. * optarg - This is set to the argument associated with any option found by
  12. * getopt that takes an argument.
  13. *
  14. * optind - Index in argv of the next element to be scanned.
  15. *
  16. * opterr - Caller sets to 0 to inhibit error status messages.
  17. *
  18. * =============================================================================
  19. * EXPORTED FUNCTIONS
  20. *
  21. * getopt - Arguments processing function.
  22. *
  23. * =============================================================================
  24. */
  25. #include <stdio.h>
  26. #include <stdlib.h>
  27. #include <string.h>
  28. //#include <mem.h>
  29. #include "getopt.h"
  30. /* This version of `getopt' appears to the caller like standard Unix `getopt'
  31. but it behaves differently for the user, since it allows the user
  32. to intersperse the options with the other arguments.
  33. As `getopt' works, it permutes the elements of `argv' so that,
  34. when it is done, all the options precede everything else. Thus
  35. all application programs are extended to handle flexible argument order.
  36. Setting the environment variable _POSIX_OPTION_ORDER disables permutation.
  37. Then the behavior is completely standard.
  38. GNU application programs can use a third alternative mode in which
  39. they can distinguish the relative order of options and other arguments. */
  40. /* =============================================================================
  41. * Exported variables
  42. */
  43. char *optarg = 0;
  44. int optind = 0;
  45. int opterr = 1;
  46. /* =============================================================================
  47. * Local variables
  48. */
  49. /*
  50. * The next char to be scanned in the option-element
  51. * in which the last option character we returned was found.
  52. * This allows us to pick up the scan where we left off.
  53. *
  54. * If this is zero, or a null string, it means resume the scan
  55. * by advancing to the next ARGV-element.
  56. */
  57. static char *nextchar;
  58. /* Describe how to deal with options that follow non-option ARGV-elements.
  59. If the caller did not specify anything,
  60. the default is REQUIRE_ORDER if the environment variable
  61. _POSIX_OPTION_ORDER is defined, PERMUTE otherwise.
  62. REQUIRE_ORDER means don't recognize them as options;
  63. stop option processing when the first non-option is seen.
  64. This is what Unix does.
  65. This mode of operation is selected by either setting the environment
  66. variable _POSIX_OPTION_ORDER, or using `+' as the first character
  67. of the list of option characters.
  68. PERMUTE is the default. We permute the contents of ARGV as we scan,
  69. so that eventually all the non-options are at the end. This allows options
  70. to be given in any order, even with programs that were not written to
  71. expect this.
  72. RETURN_IN_ORDER is an option available to programs that were written
  73. to expect options and other ARGV-elements in any order and that care about
  74. the ordering of the two. We describe each non-option ARGV-element
  75. as if it were the argument of an option with character code 1.
  76. Using `-' as the first character of the list of option characters
  77. selects this mode of operation.
  78. The special argument `--' forces an end of option-scanning regardless
  79. of the value of `ordering'. In the case of RETURN_IN_ORDER, only
  80. `--' can cause `getopt' to return EOF with `optind' != ARGC. */
  81. static enum { REQUIRE_ORDER, PERMUTE, RETURN_IN_ORDER } ordering;
  82. /* Describe the long-named options requested by the application.
  83. _GETOPT_LONG_OPTIONS is a vector of `struct option' terminated by an
  84. element containing a name which is zero.
  85. The field `has_arg' is 1 if the option takes an argument,
  86. 2 if it takes an optional argument. */
  87. struct option {
  88. char *name;
  89. int has_arg;
  90. int *flag;
  91. int val;
  92. };
  93. const struct option *_getopt_long_options;
  94. int _getopt_long_only = 0;
  95. /* Index in _GETOPT_LONG_OPTIONS of the long-named option actually found.
  96. Only valid when a long-named option was found. */
  97. int option_index;
  98. /* Handle permutation of arguments. */
  99. /* Describe the part of ARGV that contains non-options that have
  100. been skipped. `first_nonopt' is the index in ARGV of the first of them;
  101. `last_nonopt' is the index after the last of them. */
  102. static int first_nonopt;
  103. static int last_nonopt;
  104. /* =============================================================================
  105. * Local functions
  106. */
  107. /* Exchange two adjacent subsequences of ARGV.
  108. One subsequence is elements [first_nonopt,last_nonopt)
  109. which contains all the non-options that have been skipped so far.
  110. The other is elements [last_nonopt,optind), which contains all
  111. the options processed since those non-options were skipped.
  112. `first_nonopt' and `last_nonopt' are relocated so that they describe
  113. the new indices of the non-options in ARGV after they are moved. */
  114. static void exchange(char **argv) {
  115. int nonopts_size = (last_nonopt - first_nonopt) * sizeof(char *);
  116. char **temp = (char **)malloc(nonopts_size);
  117. /* Interchange the two blocks of data in ARGV. */
  118. memcpy(&argv[first_nonopt], temp, nonopts_size);
  119. memcpy(&argv[last_nonopt], &argv[first_nonopt],
  120. (optind - last_nonopt) * sizeof(char *));
  121. memcpy(temp, &argv[first_nonopt + optind - last_nonopt], nonopts_size);
  122. /* Update records for the slots the non-options now occupy. */
  123. first_nonopt += (optind - last_nonopt);
  124. last_nonopt = optind;
  125. free(temp);
  126. }
  127. /* =============================================================================
  128. * Exported functions
  129. */
  130. /* =============================================================================
  131. * FUNCTION: ugetopt
  132. */
  133. int ugetopt(int argc, char **argv, const char *optstring) {
  134. optarg = 0;
  135. /* Initialize the internal data when the first call is made.
  136. Start processing options with ARGV-element 1 (since ARGV-element 0
  137. is the program name); the sequence of previously skipped
  138. non-option ARGV-elements is empty.
  139. */
  140. if (optind == 0) {
  141. first_nonopt = last_nonopt = optind = 1;
  142. nextchar = 0;
  143. /* Determine how to handle the ordering of options and nonoptions. */
  144. if (optstring[0] == '-') {
  145. ordering = RETURN_IN_ORDER;
  146. ++optstring;
  147. } else if (optstring[0] == '+') {
  148. ordering = REQUIRE_ORDER;
  149. ++optstring;
  150. } else if (getenv("_POSIX_OPTION_ORDER") != 0)
  151. ordering = REQUIRE_ORDER;
  152. else
  153. ordering = PERMUTE;
  154. }
  155. if (nextchar == 0 || *nextchar == 0) {
  156. if (ordering == PERMUTE) {
  157. /* If we have just processed some options following some non-options,
  158. exchange them so that the options come first. */
  159. if (first_nonopt != last_nonopt && last_nonopt != optind)
  160. exchange(argv);
  161. else if (last_nonopt != optind)
  162. first_nonopt = optind;
  163. /* Now skip any additional non-options
  164. and extend the range of non-options previously skipped. */
  165. while ((optind < argc) &&
  166. ((argv[optind][0] != '-') || (argv[optind][1] == 0)) &&
  167. ((_getopt_long_options == 0) || (argv[optind][0] != '+') ||
  168. (argv[optind][1] == 0)))
  169. optind++;
  170. last_nonopt = optind;
  171. }
  172. /* Special ARGV-element `--' means premature end of options.
  173. Skip it like a null option,
  174. then exchange with previous non-options as if it were an option,
  175. then skip everything else like a non-option.
  176. */
  177. if (optind != argc && !strcmp(argv[optind], "--")) {
  178. optind++;
  179. if (first_nonopt != last_nonopt && last_nonopt != optind)
  180. exchange(argv);
  181. else if (first_nonopt == last_nonopt)
  182. first_nonopt = optind;
  183. last_nonopt = argc;
  184. optind = argc;
  185. }
  186. /* If we have done all the ARGV-elements, stop the scan
  187. and back over any non-options that we skipped and permuted.
  188. */
  189. if (optind == argc) {
  190. /* Set the next-arg-index to point at the non-options
  191. that we previously skipped, so the caller will digest them.
  192. */
  193. if (first_nonopt != last_nonopt)
  194. optind = first_nonopt;
  195. return EOF;
  196. }
  197. /* If we have come to a non-option and did not permute it,
  198. either stop the scan or describe it to the caller and pass it by.
  199. */
  200. if (((argv[optind][0] != '-') || (argv[optind][1] == 0)) &&
  201. ((_getopt_long_options == 0) || (argv[optind][0] != '+') ||
  202. (argv[optind][1] == 0))) {
  203. if (ordering == REQUIRE_ORDER)
  204. return EOF;
  205. optarg = argv[optind++];
  206. return 1;
  207. }
  208. /* We have found another option-ARGV-element.
  209. Start decoding its characters.
  210. */
  211. nextchar = argv[optind] + 1;
  212. }
  213. if ((_getopt_long_options != 0) &&
  214. ((argv[optind][0] == '+') ||
  215. (_getopt_long_only && (argv[optind][0] == '-')))) {
  216. const struct option *p;
  217. char *s = nextchar;
  218. int exact = 0;
  219. int ambig = 0;
  220. const struct option *pfound = 0;
  221. int indfound = NULL;
  222. while (*s && (*s != '='))
  223. s++;
  224. /* Test all options for either exact match or abbreviated matches. */
  225. for (p = _getopt_long_options, option_index = 0; p->name;
  226. p++, option_index++) {
  227. if (!strncmp(p->name, nextchar, s - nextchar)) {
  228. if (s - nextchar == (unsigned)strlen(p->name)) {
  229. /* Exact match found. */
  230. pfound = p;
  231. indfound = option_index;
  232. exact = 1;
  233. break;
  234. } else if (pfound == 0) {
  235. /* First nonexact match found. */
  236. pfound = p;
  237. indfound = option_index;
  238. } else
  239. /* Second nonexact match found. */
  240. ambig = 1;
  241. }
  242. }
  243. if (ambig && !exact) {
  244. fprintf(stderr, "%s: option `%s' is ambiguous\n", argv[0], argv[optind]);
  245. nextchar += strlen(nextchar);
  246. optind++;
  247. return '?';
  248. }
  249. if (pfound != 0) {
  250. option_index = indfound;
  251. optind++;
  252. if (*s) {
  253. if (pfound->has_arg > 0)
  254. optarg = s + 1;
  255. else {
  256. fprintf(stderr, "%s: option `%c%s' doesn't allow an argument\n",
  257. argv[0], argv[optind - 1][0], pfound->name);
  258. nextchar += strlen(nextchar);
  259. return '?';
  260. }
  261. } else if (pfound->has_arg == 1) {
  262. if (optind < argc)
  263. optarg = argv[optind++];
  264. else {
  265. fprintf(stderr, "%s: option `%s' requires an argument\n", argv[0],
  266. argv[optind - 1]);
  267. nextchar += strlen(nextchar);
  268. return '?';
  269. }
  270. }
  271. nextchar += strlen(nextchar);
  272. if (pfound->flag) {
  273. *(pfound->flag) = pfound->val;
  274. return 0;
  275. }
  276. return pfound->val;
  277. }
  278. /* Can't find it as a long option. If this is getopt_long_only,
  279. and the option starts with '-' and is a valid short
  280. option, then interpret it as a short option. Otherwise it's
  281. an error.
  282. */
  283. if ((_getopt_long_only == 0) || (argv[optind][0] == '+') ||
  284. (strchr(optstring, *nextchar) == 0)) {
  285. if (opterr != 0) {
  286. fprintf(stderr, "%s: unrecognized option `%c%s'\n", argv[0],
  287. argv[optind][0], nextchar);
  288. }
  289. nextchar += strlen(nextchar);
  290. optind++;
  291. return '?';
  292. }
  293. }
  294. /* Look at and handle the next option-character. */
  295. {
  296. char c = *nextchar++;
  297. const char *temp = strchr(optstring, c);
  298. /* Increment `optind' when we start to process its last character. */
  299. if (*nextchar == 0)
  300. optind++;
  301. if (temp == 0 || c == ':') {
  302. if (opterr != 0) {
  303. if (c < 040 || c >= 0177)
  304. fprintf(stderr, "%s: unrecognized option, character code 0%o\n",
  305. argv[0], c);
  306. else
  307. fprintf(stderr, "%s: unrecognized option `-%c'\n", argv[0], c);
  308. }
  309. return '?';
  310. }
  311. if (temp[1] == ':') {
  312. if (temp[2] == ':') {
  313. /* This is an option that accepts an argument optionally. */
  314. if (*nextchar != 0) {
  315. optarg = nextchar;
  316. optind++;
  317. } else
  318. optarg = 0;
  319. nextchar = 0;
  320. } else {
  321. /* This is an option that requires an argument. */
  322. if (*nextchar != 0) {
  323. optarg = nextchar;
  324. /* If we end this ARGV-element by taking the rest as an arg,
  325. we must advance to the next element now.
  326. */
  327. optind++;
  328. } else if (optind == argc) {
  329. if (opterr != 0) {
  330. fprintf(stderr, "%s: option `-%c' requires an argument\n", argv[0],
  331. c);
  332. }
  333. c = '?';
  334. } else
  335. /* We already incremented `optind' once;
  336. increment it again when taking next ARGV-elt as argument. */
  337. optarg = argv[optind++];
  338. nextchar = 0;
  339. }
  340. }
  341. return c;
  342. }
  343. }