getopt.c 12 KB

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