GETOPT.C 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494
  1. #define alloca malloc
  2. #define USG
  3. /* Getopt for GNU.
  4. Copyright (C) 1987, 1989 Free Software Foundation, Inc.
  5. This program is free software; you can redistribute it and/or modify
  6. it under the terms of the GNU General Public License as published by
  7. the Free Software Foundation; either version 1, or (at your option)
  8. any later version.
  9. This program is distributed in the hope that it will be useful,
  10. but WITHOUT ANY WARRANTY; without even the implied warranty of
  11. MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  12. GNU General Public License for more details.
  13. You should have received a copy of the GNU General Public License
  14. along with this program; if not, write to the Free Software
  15. Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. */
  16. /* This version of `getopt' appears to the caller like standard Unix `getopt'
  17. but it behaves differently for the user, since it allows the user
  18. to intersperse the options with the other arguments.
  19. As `getopt' works, it permutes the elements of `argv' so that,
  20. when it is done, all the options precede everything else. Thus
  21. all application programs are extended to handle flexible argument order.
  22. Setting the environment variable _POSIX_OPTION_ORDER disables permutation.
  23. Then the behavior is completely standard.
  24. GNU application programs can use a third alternative mode in which
  25. they can distinguish the relative order of options and other arguments. */
  26. #include <stdio.h>
  27. #include <stdlib.h>
  28. #include <string.h>
  29. /* If compiled with GNU C, use the built-in alloca */
  30. #ifdef __GNUC__
  31. #define alloca __builtin_alloca
  32. #else /* not __GNUC__ */
  33. #ifdef sparc
  34. #include <alloca.h>
  35. #endif
  36. #endif /* not __GNUC__ */
  37. #ifdef USG
  38. #define bcopy(s, d, l) memcpy((d), (s), (l))
  39. #define index strchr
  40. #endif
  41. /* For communication from `getopt' to the caller.
  42. When `getopt' finds an option that takes an argument,
  43. the argument value is returned here.
  44. Also, when `ordering' is RETURN_IN_ORDER,
  45. each non-option ARGV-element is returned here. */
  46. char *optarg = 0;
  47. /* Index in ARGV of the next element to be scanned.
  48. This is used for communication to and from the caller
  49. and for communication between successive calls to `getopt'.
  50. On entry to `getopt', zero means this is the first call; initialize.
  51. When `getopt' returns EOF, this is the index of the first of the
  52. non-option elements that the caller should itself scan.
  53. Otherwise, `optind' communicates from one call to the next
  54. how much of ARGV has been scanned so far. */
  55. int optind = 0;
  56. /* The next char to be scanned in the option-element
  57. in which the last option character we returned was found.
  58. This allows us to pick up the scan where we left off.
  59. If this is zero, or a null string, it means resume the scan
  60. by advancing to the next ARGV-element. */
  61. static char *nextchar;
  62. /* Callers store zero here to inhibit the error message
  63. for unrecognized options. */
  64. int opterr = 1;
  65. /* Describe how to deal with options that follow non-option ARGV-elements.
  66. UNSPECIFIED means the caller did not specify anything;
  67. the default is then REQUIRE_ORDER if the environment variable
  68. _OPTIONS_FIRST is defined, PERMUTE otherwise.
  69. REQUIRE_ORDER means don't recognize them as options.
  70. Stop option processing when the first non-option is seen.
  71. This is what Unix does.
  72. PERMUTE is the default. We permute the contents of `argv' as we scan,
  73. so that eventually all the options are at the end. This allows options
  74. to be given in any order, even with programs that were not written to
  75. expect this.
  76. RETURN_IN_ORDER is an option available to programs that were written
  77. to expect options and other ARGV-elements in any order and that care about
  78. the ordering of the two. We describe each non-option ARGV-element
  79. as if it were the argument of an option with character code zero.
  80. Using `-' as the first character of the list of option characters
  81. requests this mode of operation.
  82. The special argument `--' forces an end of option-scanning regardless
  83. of the value of `ordering'. In the case of RETURN_IN_ORDER, only
  84. `--' can cause `getopt' to return EOF with `optind' != ARGC. */
  85. static enum { REQUIRE_ORDER, PERMUTE, RETURN_IN_ORDER } ordering;
  86. /* Describe the long-named options requested by the application.
  87. _GETOPT_LONG_OPTIONS is a vector of `struct option' terminated by an
  88. element containing a name which is zero.
  89. The field `has_arg' is 1 if the option takes an argument,
  90. 2 if it takes an optional argument. */
  91. struct option
  92. {
  93. char *name;
  94. int has_arg;
  95. int *flag;
  96. int val;
  97. };
  98. struct option *_getopt_long_options;
  99. /* Name of long-named option actually found. */
  100. char *_getopt_option_name = '\0';
  101. int option_index = 0;
  102. /* Handle permutation of arguments. */
  103. /* Describe the part of ARGV that contains non-options that have
  104. been skipped. `first_nonopt' is the index in ARGV of the first of them;
  105. `last_nonopt' is the index after the last of them. */
  106. static int first_nonopt;
  107. static int last_nonopt;
  108. /* Exchange two adjacent subsequences of ARGV.
  109. One subsequence is elements [first_nonopt,last_nonopt)
  110. which contains all the non-options that have been skipped so far.
  111. The other is elements [last_nonopt,optind), which contains all
  112. the options processed since those non-options were skipped.
  113. `first_nonopt' and `last_nonopt' are relocated so that they describe
  114. the new indices of the non-options in ARGV after they are moved. */
  115. static void
  116. exchange (argv)
  117. char **argv;
  118. {
  119. int nonopts_size
  120. = (last_nonopt - first_nonopt) * sizeof (char *);
  121. char **temp = (char **) alloca (nonopts_size);
  122. /* Interchange the two blocks of data in argv. */
  123. bcopy (&argv[first_nonopt], temp, nonopts_size);
  124. bcopy (&argv[last_nonopt], &argv[first_nonopt],
  125. (optind - last_nonopt) * sizeof (char *));
  126. bcopy (temp, &argv[first_nonopt + optind - last_nonopt],
  127. nonopts_size);
  128. /* Update records for the slots the non-options now occupy. */
  129. first_nonopt += (optind - last_nonopt);
  130. last_nonopt = optind;
  131. }
  132. /* Scan elements of ARGV (whose length is ARGC) for option characters
  133. given in OPTSTRING.
  134. If an element of ARGV starts with '-', and is not exactly "-" or "--",
  135. then it is an option element. The characters of this element
  136. (aside from the initial '-') are option characters. If `getopt'
  137. is called repeatedly, it returns successively each of theoption characters
  138. from each of the option elements.
  139. If `getopt' finds another option character, it returns that character,
  140. updating `optind' and `nextchar' so that the next call to `getopt' can
  141. resume the scan with the following option character or ARGV-element.
  142. If there are no more option characters, `getopt' returns `EOF'.
  143. Then `optind' is the index in ARGV of the first ARGV-element
  144. that is not an option. (The ARGV-elements have been permuted
  145. so that those that are not options now come last.)
  146. OPTSTRING is a string containing the legitimate option characters.
  147. A colon in OPTSTRING means that the previous character is an option
  148. that wants an argument. The argument is taken from the rest of the
  149. current ARGV-element, or from the following ARGV-element,
  150. and returned in `optarg'.
  151. If an option character is seen that is not listed in OPTSTRING,
  152. return '?' after printing an error message. If you set `opterr' to
  153. zero, the error message is suppressed but we still return '?'.
  154. If a char in OPTSTRING is followed by a colon, that means it wants an arg,
  155. so the following text in the same ARGV-element, or the text of the following
  156. ARGV-element, is returned in `optarg. Two colons mean an option that
  157. wants an optional arg; if there is text in the current ARGV-element,
  158. it is returned in `optarg'.
  159. If OPTSTRING starts with `-', it requests a different method of handling the
  160. non-option ARGV-elements. See the comments about RETURN_IN_ORDER, above. */
  161. int
  162. getopt (argc, argv, optstring)
  163. int argc;
  164. char **argv;
  165. char *optstring;
  166. {
  167. optarg = 0;
  168. /* Initialize the internal data when the first call is made.
  169. Start processing options with ARGV-element 1 (since ARGV-element 0
  170. is the program name); the sequence of previously skipped
  171. non-option ARGV-elements is empty. */
  172. if (optind == 0)
  173. {
  174. first_nonopt = last_nonopt = optind = 1;
  175. nextchar = 0;
  176. /* Determine how to handle the ordering of options and nonoptions. */
  177. if (optstring[0] == '-')
  178. ordering = RETURN_IN_ORDER;
  179. else if (getenv ("_POSIX_OPTION_ORDER") != 0)
  180. ordering = REQUIRE_ORDER;
  181. else
  182. ordering = PERMUTE;
  183. }
  184. if (nextchar == 0 || *nextchar == 0)
  185. {
  186. if (ordering == PERMUTE)
  187. {
  188. /* If we have just processed some options following some non-options,
  189. exchange them so that the options come first. */
  190. if (first_nonopt != last_nonopt && last_nonopt != optind)
  191. exchange (argv);
  192. else if (last_nonopt != optind)
  193. first_nonopt = optind;
  194. /* Now skip any additional non-options
  195. and extend the range of non-options previously skipped. */
  196. while (optind < argc
  197. && (argv[optind][0] != '-'
  198. || argv[optind][1] == 0)
  199. && (argv[optind][0] != '+'
  200. || argv[optind][1] == 0))
  201. optind++;
  202. last_nonopt = optind;
  203. }
  204. /* Special ARGV-element `--' means premature end of options.
  205. Skip it like a null option,
  206. then exchange with previous non-options as if it were an option,
  207. then skip everything else like a non-option. */
  208. if (optind != argc && !strcmp (argv[optind], "--"))
  209. {
  210. optind++;
  211. if (first_nonopt != last_nonopt && last_nonopt != optind)
  212. exchange (argv);
  213. else if (first_nonopt == last_nonopt)
  214. first_nonopt = optind;
  215. last_nonopt = argc;
  216. optind = argc;
  217. }
  218. /* If we have done all the ARGV-elements, stop the scan
  219. and back over any non-options that we skipped and permuted. */
  220. if (optind == argc)
  221. {
  222. /* Set the next-arg-index to point at the non-options
  223. that we previously skipped, so the caller will digest them. */
  224. if (first_nonopt != last_nonopt)
  225. optind = first_nonopt;
  226. return EOF;
  227. }
  228. /* If we have come to a non-option and did not permute it,
  229. either stop the scan or describe it to the caller and pass it by. */
  230. if ((argv[optind][0] != '-' || argv[optind][1] == 0)
  231. && (argv[optind][0] != '+' || argv[optind][1] == 0))
  232. {
  233. if (ordering == REQUIRE_ORDER)
  234. return EOF;
  235. optarg = argv[optind++];
  236. return 0;
  237. }
  238. /* We have found another option-ARGV-element.
  239. Start decoding its characters. */
  240. nextchar = argv[optind] + 1;
  241. }
  242. if (_getopt_long_options != 0 && argv[optind][0] == '+') {
  243. struct option *p;
  244. char *s = nextchar;
  245. while (*s && *s != '=') s++;
  246. for (p = _getopt_long_options, option_index = 0; p->name;
  247. p++, option_index++) {
  248. if (!strncmp (p->name, nextchar, s - nextchar))
  249. {
  250. optind++;
  251. if (*s)
  252. {
  253. if (p->has_arg > 0)
  254. optarg = s + 1;
  255. else {
  256. fprintf (stderr, "%s: option +%s doesn't allow an argument\n",
  257. argv[0], p->name);
  258. nextchar += strlen (nextchar);
  259. return '?';
  260. }
  261. }
  262. else if (p->has_arg)
  263. {
  264. if (optind + 1 < argc)
  265. optarg = argv[optind++];
  266. else if (p->has_arg != 2) {
  267. fprintf (stderr, "%s: option +%s requires an argument\n",
  268. argv[0], p->name);
  269. nextchar += strlen (nextchar);
  270. return '?';
  271. }
  272. }
  273. _getopt_option_name = p->name;
  274. nextchar += strlen (nextchar);
  275. if (p->flag)
  276. *(p->flag) = p->val;
  277. return 0;
  278. }
  279. }
  280. }
  281. /* Look at and handle the next option-character. */
  282. {
  283. char c = *nextchar++;
  284. char *temp = (char *) index (optstring, c);
  285. /* Increment `optind' when we start to process its last character. */
  286. if (*nextchar == 0)
  287. optind++;
  288. if (temp == 0 || c == ':')
  289. {
  290. if (opterr != 0)
  291. {
  292. if (c < 040 || c >= 0177)
  293. fprintf (stderr, "%s: unrecognized option, character code 0%o\n",
  294. argv[0], c);
  295. else
  296. fprintf (stderr, "%s: unrecognized option `-%c'\n",
  297. argv[0], c);
  298. }
  299. return '?';
  300. }
  301. if (temp[1] == ':')
  302. {
  303. if (temp[2] == ':')
  304. {
  305. /* This is an option that accepts an argument optionally. */
  306. if (*nextchar != 0)
  307. {
  308. optarg = nextchar;
  309. optind++;
  310. }
  311. else
  312. optarg = 0;
  313. nextchar = 0;
  314. }
  315. else
  316. {
  317. /* This is an option that requires an argument. */
  318. if (*nextchar != 0)
  319. {
  320. optarg = nextchar;
  321. /* If we end this ARGV-element by taking the rest as an arg,
  322. we must advance to the next element now. */
  323. optind++;
  324. }
  325. else if (optind == argc)
  326. {
  327. if (opterr != 0)
  328. fprintf (stderr, "%s: no argument for `-%c' option\n",
  329. argv[0], c);
  330. c = '?';
  331. }
  332. else
  333. /* We already incremented `optind' once;
  334. increment it again when taking next ARGV-elt as argument. */
  335. optarg = argv[optind++];
  336. nextchar = 0;
  337. }
  338. }
  339. return c;
  340. }
  341. }
  342. #ifdef TEST
  343. /* Compile with -DTEST to make an executable for use in testing
  344. the above definition of `getopt'. */
  345. int
  346. main (argc, argv)
  347. int argc;
  348. char **argv;
  349. {
  350. char c;
  351. int digit_optind = 0;
  352. while (1)
  353. {
  354. int this_option_optind = optind;
  355. if ((c = getopt (argc, argv, "abc:d:0123456789")) == EOF)
  356. break;
  357. switch (c)
  358. {
  359. case '0':
  360. case '1':
  361. case '2':
  362. case '3':
  363. case '4':
  364. case '5':
  365. case '6':
  366. case '7':
  367. case '8':
  368. case '9':
  369. if (digit_optind != 0 && digit_optind != this_option_optind)
  370. printf ("digits occur in two different argv-elements.\n");
  371. digit_optind = this_option_optind;
  372. printf ("option %c\n", c);
  373. break;
  374. case 'a':
  375. printf ("option a\n");
  376. break;
  377. case 'b':
  378. printf ("option b\n");
  379. break;
  380. case 'c':
  381. printf ("option c with value `%s'\n", optarg);
  382. break;
  383. case '?':
  384. break;
  385. default:
  386. printf ("?? getopt returned character code 0%o ??\n", c);
  387. }
  388. }
  389. if (optind < argc)
  390. {
  391. printf ("non-option ARGV-elements: ");
  392. while (optind < argc)
  393. printf ("%s ", argv[optind++]);
  394. printf ("\n");
  395. }
  396. return 0;
  397. }
  398. #endif /* TEST */
  399.