getopt.c 29 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056
  1. /* Getopt for GNU.
  2. NOTE: getopt is now part of the C library, so if you don't know what
  3. "Keep this file name-space clean" means, talk to drepper@gnu.org
  4. before changing it!
  5. Copyright (C) 1987,88,89,90,91,92,93,94,95,96,98,99,2000,2001
  6. Free Software Foundation, Inc.
  7. This file is part of the GNU C Library.
  8. The GNU C Library is free software; you can redistribute it and/or
  9. modify it under the terms of the GNU Lesser General Public
  10. License as published by the Free Software Foundation; either
  11. version 2.1 of the License, or (at your option) any later version.
  12. The GNU C Library is distributed in the hope that it will be useful,
  13. but WITHOUT ANY WARRANTY; without even the implied warranty of
  14. MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
  15. Lesser General Public License for more details.
  16. You should have received a copy of the GNU Lesser General Public
  17. License along with the GNU C Library; if not, write to the Free
  18. Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA
  19. 02111-1307 USA. */
  20. /* This tells Alpha OSF/1 not to define a getopt prototype in <stdio.h>.
  21. Ditto for AIX 3.2 and <stdlib.h>. */
  22. #ifndef _NO_PROTO
  23. # define _NO_PROTO
  24. #endif
  25. #ifdef HAVE_CONFIG_H
  26. # include <config.h>
  27. #endif
  28. #if !defined __STDC__ || !__STDC__
  29. /* This is a separate conditional since some stdc systems
  30. reject `defined (const)'. */
  31. # ifndef const
  32. # define const
  33. # endif
  34. #endif
  35. #include <stdio.h>
  36. /* Comment out all this code if we are using the GNU C Library, and are not
  37. actually compiling the library itself. This code is part of the GNU C
  38. Library, but also included in many other GNU distributions. Compiling
  39. and linking in this code is a waste when using the GNU C library
  40. (especially if it is a shared library). Rather than having every GNU
  41. program understand `configure --with-gnu-libc' and omit the object files,
  42. it is simpler to just do this in the source for each such file. */
  43. #define GETOPT_INTERFACE_VERSION 2
  44. #if !defined _LIBC && defined __GLIBC__ && __GLIBC__ >= 2
  45. # include <gnu-versions.h>
  46. # if _GNU_GETOPT_INTERFACE_VERSION == GETOPT_INTERFACE_VERSION
  47. # define ELIDE_CODE
  48. # endif
  49. #endif
  50. #ifndef ELIDE_CODE
  51. /* This needs to come after some library #include
  52. to get __GNU_LIBRARY__ defined. */
  53. #ifdef __GNU_LIBRARY__
  54. /* Don't include stdlib.h for non-GNU C libraries because some of them
  55. contain conflicting prototypes for getopt. */
  56. # include <stdlib.h>
  57. # include <unistd.h>
  58. #endif /* GNU C library. */
  59. #ifdef VMS
  60. # include <unixlib.h>
  61. # if HAVE_STRING_H - 0
  62. # include <string.h>
  63. # endif
  64. #endif
  65. #ifndef _
  66. /* This is for other GNU distributions with internationalized messages. */
  67. # if defined HAVE_LIBINTL_H || defined _LIBC
  68. # include <libintl.h>
  69. # ifndef _
  70. # define _(msgid) gettext (msgid)
  71. # endif
  72. # else
  73. # define _(msgid) (msgid)
  74. # endif
  75. #endif
  76. /* This version of `getopt' appears to the caller like standard Unix `getopt'
  77. but it behaves differently for the user, since it allows the user
  78. to intersperse the options with the other arguments.
  79. As `getopt' works, it permutes the elements of ARGV so that,
  80. when it is done, all the options precede everything else. Thus
  81. all application programs are extended to handle flexible argument order.
  82. Setting the environment variable POSIXLY_CORRECT disables permutation.
  83. Then the behavior is completely standard.
  84. GNU application programs can use a third alternative mode in which
  85. they can distinguish the relative order of options and other arguments. */
  86. #include "getopt.h"
  87. /* For communication from `getopt' to the caller.
  88. When `getopt' finds an option that takes an argument,
  89. the argument value is returned here.
  90. Also, when `ordering' is RETURN_IN_ORDER,
  91. each non-option ARGV-element is returned here. */
  92. char *optarg;
  93. /* Index in ARGV of the next element to be scanned.
  94. This is used for communication to and from the caller
  95. and for communication between successive calls to `getopt'.
  96. On entry to `getopt', zero means this is the first call; initialize.
  97. When `getopt' returns -1, this is the index of the first of the
  98. non-option elements that the caller should itself scan.
  99. Otherwise, `optind' communicates from one call to the next
  100. how much of ARGV has been scanned so far. */
  101. /* 1003.2 says this must be 1 before any call. */
  102. int optind = 1;
  103. /* Formerly, initialization of getopt depended on optind==0, which
  104. causes problems with re-calling getopt as programs generally don't
  105. know that. */
  106. int __getopt_initialized;
  107. /* The next char to be scanned in the option-element
  108. in which the last option character we returned was found.
  109. This allows us to pick up the scan where we left off.
  110. If this is zero, or a null string, it means resume the scan
  111. by advancing to the next ARGV-element. */
  112. static char *nextchar;
  113. /* Callers store zero here to inhibit the error message
  114. for unrecognized options. */
  115. int opterr = 1;
  116. /* Set to an option character which was unrecognized.
  117. This must be initialized on some systems to avoid linking in the
  118. system's own getopt implementation. */
  119. int optopt = '?';
  120. /* Describe how to deal with options that follow non-option ARGV-elements.
  121. If the caller did not specify anything,
  122. the default is REQUIRE_ORDER if the environment variable
  123. POSIXLY_CORRECT is defined, PERMUTE otherwise.
  124. REQUIRE_ORDER means don't recognize them as options;
  125. stop option processing when the first non-option is seen.
  126. This is what Unix does.
  127. This mode of operation is selected by either setting the environment
  128. variable POSIXLY_CORRECT, or using `+' as the first character
  129. of the list of option characters.
  130. PERMUTE is the default. We permute the contents of ARGV as we scan,
  131. so that eventually all the non-options are at the end. This allows options
  132. to be given in any order, even with programs that were not written to
  133. expect this.
  134. RETURN_IN_ORDER is an option available to programs that were written
  135. to expect options and other ARGV-elements in any order and that care about
  136. the ordering of the two. We describe each non-option ARGV-element
  137. as if it were the argument of an option with character code 1.
  138. Using `-' as the first character of the list of option characters
  139. selects this mode of operation.
  140. The special argument `--' forces an end of option-scanning regardless
  141. of the value of `ordering'. In the case of RETURN_IN_ORDER, only
  142. `--' can cause `getopt' to return -1 with `optind' != ARGC. */
  143. static enum
  144. {
  145. REQUIRE_ORDER, PERMUTE, RETURN_IN_ORDER
  146. } ordering;
  147. /* Value of POSIXLY_CORRECT environment variable. */
  148. static char *posixly_correct;
  149. #ifdef __GNU_LIBRARY__
  150. /* We want to avoid inclusion of string.h with non-GNU libraries
  151. because there are many ways it can cause trouble.
  152. On some systems, it contains special magic macros that don't work
  153. in GCC. */
  154. # include <string.h>
  155. # define my_index strchr
  156. #else
  157. # if HAVE_STRING_H
  158. # include <string.h>
  159. # else
  160. # include <strings.h>
  161. # endif
  162. /* Avoid depending on library functions or files
  163. whose names are inconsistent. */
  164. #ifndef getenv
  165. extern char *getenv ();
  166. #endif
  167. static char *
  168. my_index (str, chr)
  169. const char *str;
  170. int chr;
  171. {
  172. while (*str)
  173. {
  174. if (*str == chr)
  175. return (char *) str;
  176. str++;
  177. }
  178. return 0;
  179. }
  180. /* If using GCC, we can safely declare strlen this way.
  181. If not using GCC, it is ok not to declare it. */
  182. #ifdef __GNUC__
  183. /* Note that Motorola Delta 68k R3V7 comes with GCC but not stddef.h.
  184. That was relevant to code that was here before. */
  185. # if (!defined __STDC__ || !__STDC__) && !defined strlen
  186. /* gcc with -traditional declares the built-in strlen to return int,
  187. and has done so at least since version 2.4.5. -- rms. */
  188. extern int strlen (const char *);
  189. # endif /* not __STDC__ */
  190. #endif /* __GNUC__ */
  191. #endif /* not __GNU_LIBRARY__ */
  192. /* Handle permutation of arguments. */
  193. /* Describe the part of ARGV that contains non-options that have
  194. been skipped. `first_nonopt' is the index in ARGV of the first of them;
  195. `last_nonopt' is the index after the last of them. */
  196. static int first_nonopt;
  197. static int last_nonopt;
  198. #ifdef _LIBC
  199. /* Stored original parameters.
  200. XXX This is no good solution. We should rather copy the args so
  201. that we can compare them later. But we must not use malloc(3). */
  202. extern int __libc_argc;
  203. extern char **__libc_argv;
  204. /* Bash 2.0 gives us an environment variable containing flags
  205. indicating ARGV elements that should not be considered arguments. */
  206. # ifdef USE_NONOPTION_FLAGS
  207. /* Defined in getopt_init.c */
  208. extern char *__getopt_nonoption_flags;
  209. static int nonoption_flags_max_len;
  210. static int nonoption_flags_len;
  211. # endif
  212. # ifdef USE_NONOPTION_FLAGS
  213. # define SWAP_FLAGS(ch1, ch2) \
  214. if (nonoption_flags_len > 0) \
  215. { \
  216. char __tmp = __getopt_nonoption_flags[ch1]; \
  217. __getopt_nonoption_flags[ch1] = __getopt_nonoption_flags[ch2]; \
  218. __getopt_nonoption_flags[ch2] = __tmp; \
  219. }
  220. # else
  221. # define SWAP_FLAGS(ch1, ch2)
  222. # endif
  223. #else /* !_LIBC */
  224. # define SWAP_FLAGS(ch1, ch2)
  225. #endif /* _LIBC */
  226. /* Exchange two adjacent subsequences of ARGV.
  227. One subsequence is elements [first_nonopt,last_nonopt)
  228. which contains all the non-options that have been skipped so far.
  229. The other is elements [last_nonopt,optind), which contains all
  230. the options processed since those non-options were skipped.
  231. `first_nonopt' and `last_nonopt' are relocated so that they describe
  232. the new indices of the non-options in ARGV after they are moved. */
  233. #if defined __STDC__ && __STDC__
  234. static void exchange (char **);
  235. #endif
  236. static void
  237. exchange (argv)
  238. char **argv;
  239. {
  240. int bottom = first_nonopt;
  241. int middle = last_nonopt;
  242. int top = optind;
  243. char *tem;
  244. /* Exchange the shorter segment with the far end of the longer segment.
  245. That puts the shorter segment into the right place.
  246. It leaves the longer segment in the right place overall,
  247. but it consists of two parts that need to be swapped next. */
  248. #if defined _LIBC && defined USE_NONOPTION_FLAGS
  249. /* First make sure the handling of the `__getopt_nonoption_flags'
  250. string can work normally. Our top argument must be in the range
  251. of the string. */
  252. if (nonoption_flags_len > 0 && top >= nonoption_flags_max_len)
  253. {
  254. /* We must extend the array. The user plays games with us and
  255. presents new arguments. */
  256. char *new_str = malloc (top + 1);
  257. if (new_str == NULL)
  258. nonoption_flags_len = nonoption_flags_max_len = 0;
  259. else
  260. {
  261. memset (__mempcpy (new_str, __getopt_nonoption_flags,
  262. nonoption_flags_max_len),
  263. '\0', top + 1 - nonoption_flags_max_len);
  264. nonoption_flags_max_len = top + 1;
  265. __getopt_nonoption_flags = new_str;
  266. }
  267. }
  268. #endif
  269. while (top > middle && middle > bottom)
  270. {
  271. if (top - middle > middle - bottom)
  272. {
  273. /* Bottom segment is the short one. */
  274. int len = middle - bottom;
  275. register int i;
  276. /* Swap it with the top part of the top segment. */
  277. for (i = 0; i < len; i++)
  278. {
  279. tem = argv[bottom + i];
  280. argv[bottom + i] = argv[top - (middle - bottom) + i];
  281. argv[top - (middle - bottom) + i] = tem;
  282. SWAP_FLAGS (bottom + i, top - (middle - bottom) + i);
  283. }
  284. /* Exclude the moved bottom segment from further swapping. */
  285. top -= len;
  286. }
  287. else
  288. {
  289. /* Top segment is the short one. */
  290. int len = top - middle;
  291. register int i;
  292. /* Swap it with the bottom part of the bottom segment. */
  293. for (i = 0; i < len; i++)
  294. {
  295. tem = argv[bottom + i];
  296. argv[bottom + i] = argv[middle + i];
  297. argv[middle + i] = tem;
  298. SWAP_FLAGS (bottom + i, middle + i);
  299. }
  300. /* Exclude the moved top segment from further swapping. */
  301. bottom += len;
  302. }
  303. }
  304. /* Update records for the slots the non-options now occupy. */
  305. first_nonopt += (optind - last_nonopt);
  306. last_nonopt = optind;
  307. }
  308. /* Initialize the internal data when the first call is made. */
  309. #if defined __STDC__ && __STDC__
  310. static const char *_getopt_initialize (int, char *const *, const char *);
  311. #endif
  312. static const char *
  313. _getopt_initialize (argc, argv, optstring)
  314. int argc;
  315. char *const *argv;
  316. const char *optstring;
  317. {
  318. /* Start processing options with ARGV-element 1 (since ARGV-element 0
  319. is the program name); the sequence of previously skipped
  320. non-option ARGV-elements is empty. */
  321. first_nonopt = last_nonopt = optind;
  322. nextchar = NULL;
  323. posixly_correct = getenv ("POSIXLY_CORRECT");
  324. /* Determine how to handle the ordering of options and nonoptions. */
  325. if (optstring[0] == '-')
  326. {
  327. ordering = RETURN_IN_ORDER;
  328. ++optstring;
  329. }
  330. else if (optstring[0] == '+')
  331. {
  332. ordering = REQUIRE_ORDER;
  333. ++optstring;
  334. }
  335. else if (posixly_correct != NULL)
  336. ordering = REQUIRE_ORDER;
  337. else
  338. ordering = PERMUTE;
  339. #if defined _LIBC && defined USE_NONOPTION_FLAGS
  340. if (posixly_correct == NULL
  341. && argc == __libc_argc && argv == __libc_argv)
  342. {
  343. if (nonoption_flags_max_len == 0)
  344. {
  345. if (__getopt_nonoption_flags == NULL
  346. || __getopt_nonoption_flags[0] == '\0')
  347. nonoption_flags_max_len = -1;
  348. else
  349. {
  350. const char *orig_str = __getopt_nonoption_flags;
  351. int len = nonoption_flags_max_len = strlen (orig_str);
  352. if (nonoption_flags_max_len < argc)
  353. nonoption_flags_max_len = argc;
  354. __getopt_nonoption_flags =
  355. (char *) malloc (nonoption_flags_max_len);
  356. if (__getopt_nonoption_flags == NULL)
  357. nonoption_flags_max_len = -1;
  358. else
  359. memset (__mempcpy (__getopt_nonoption_flags, orig_str, len),
  360. '\0', nonoption_flags_max_len - len);
  361. }
  362. }
  363. nonoption_flags_len = nonoption_flags_max_len;
  364. }
  365. else
  366. nonoption_flags_len = 0;
  367. #endif
  368. return optstring;
  369. }
  370. /* Scan elements of ARGV (whose length is ARGC) for option characters
  371. given in OPTSTRING.
  372. If an element of ARGV starts with '-', and is not exactly "-" or "--",
  373. then it is an option element. The characters of this element
  374. (aside from the initial '-') are option characters. If `getopt'
  375. is called repeatedly, it returns successively each of the option characters
  376. from each of the option elements.
  377. If `getopt' finds another option character, it returns that character,
  378. updating `optind' and `nextchar' so that the next call to `getopt' can
  379. resume the scan with the following option character or ARGV-element.
  380. If there are no more option characters, `getopt' returns -1.
  381. Then `optind' is the index in ARGV of the first ARGV-element
  382. that is not an option. (The ARGV-elements have been permuted
  383. so that those that are not options now come last.)
  384. OPTSTRING is a string containing the legitimate option characters.
  385. If an option character is seen that is not listed in OPTSTRING,
  386. return '?' after printing an error message. If you set `opterr' to
  387. zero, the error message is suppressed but we still return '?'.
  388. If a char in OPTSTRING is followed by a colon, that means it wants an arg,
  389. so the following text in the same ARGV-element, or the text of the following
  390. ARGV-element, is returned in `optarg'. Two colons mean an option that
  391. wants an optional arg; if there is text in the current ARGV-element,
  392. it is returned in `optarg', otherwise `optarg' is set to zero.
  393. If OPTSTRING starts with `-' or `+', it requests different methods of
  394. handling the non-option ARGV-elements.
  395. See the comments about RETURN_IN_ORDER and REQUIRE_ORDER, above.
  396. Long-named options begin with `--' instead of `-'.
  397. Their names may be abbreviated as long as the abbreviation is unique
  398. or is an exact match for some defined option. If they have an
  399. argument, it follows the option name in the same ARGV-element, separated
  400. from the option name by a `=', or else the in next ARGV-element.
  401. When `getopt' finds a long-named option, it returns 0 if that option's
  402. `flag' field is nonzero, the value of the option's `val' field
  403. if the `flag' field is zero.
  404. The elements of ARGV aren't really const, because we permute them.
  405. But we pretend they're const in the prototype to be compatible
  406. with other systems.
  407. LONGOPTS is a vector of `struct option' terminated by an
  408. element containing a name which is zero.
  409. LONGIND returns the index in LONGOPT of the long-named option found.
  410. It is only valid when a long-named option has been found by the most
  411. recent call.
  412. If LONG_ONLY is nonzero, '-' as well as '--' can introduce
  413. long-named options. */
  414. int
  415. _getopt_internal (argc, argv, optstring, longopts, longind, long_only)
  416. int argc;
  417. char *const *argv;
  418. const char *optstring;
  419. const struct option *longopts;
  420. int *longind;
  421. int long_only;
  422. {
  423. int print_errors = opterr;
  424. if (optstring[0] == ':')
  425. print_errors = 0;
  426. if (argc < 1)
  427. return -1;
  428. optarg = NULL;
  429. if (optind == 0 || !__getopt_initialized)
  430. {
  431. if (optind == 0)
  432. optind = 1; /* Don't scan ARGV[0], the program name. */
  433. optstring = _getopt_initialize (argc, argv, optstring);
  434. __getopt_initialized = 1;
  435. }
  436. /* Test whether ARGV[optind] points to a non-option argument.
  437. Either it does not have option syntax, or there is an environment flag
  438. from the shell indicating it is not an option. The later information
  439. is only used when the used in the GNU libc. */
  440. #if defined _LIBC && defined USE_NONOPTION_FLAGS
  441. # define NONOPTION_P (argv[optind][0] != '-' || argv[optind][1] == '\0' \
  442. || (optind < nonoption_flags_len \
  443. && __getopt_nonoption_flags[optind] == '1'))
  444. #else
  445. # define NONOPTION_P (argv[optind][0] != '-' || argv[optind][1] == '\0')
  446. #endif
  447. if (nextchar == NULL || *nextchar == '\0')
  448. {
  449. /* Advance to the next ARGV-element. */
  450. /* Give FIRST_NONOPT & LAST_NONOPT rational values if OPTIND has been
  451. moved back by the user (who may also have changed the arguments). */
  452. if (last_nonopt > optind)
  453. last_nonopt = optind;
  454. if (first_nonopt > optind)
  455. first_nonopt = optind;
  456. if (ordering == PERMUTE)
  457. {
  458. /* If we have just processed some options following some non-options,
  459. exchange them so that the options come first. */
  460. if (first_nonopt != last_nonopt && last_nonopt != optind)
  461. exchange ((char **) argv);
  462. else if (last_nonopt != optind)
  463. first_nonopt = optind;
  464. /* Skip any additional non-options
  465. and extend the range of non-options previously skipped. */
  466. while (optind < argc && NONOPTION_P)
  467. optind++;
  468. last_nonopt = optind;
  469. }
  470. /* The special ARGV-element `--' means premature end of options.
  471. Skip it like a null option,
  472. then exchange with previous non-options as if it were an option,
  473. then skip everything else like a non-option. */
  474. if (optind != argc && !strcmp (argv[optind], "--"))
  475. {
  476. optind++;
  477. if (first_nonopt != last_nonopt && last_nonopt != optind)
  478. exchange ((char **) argv);
  479. else if (first_nonopt == last_nonopt)
  480. first_nonopt = optind;
  481. last_nonopt = argc;
  482. optind = argc;
  483. }
  484. /* If we have done all the ARGV-elements, stop the scan
  485. and back over any non-options that we skipped and permuted. */
  486. if (optind == argc)
  487. {
  488. /* Set the next-arg-index to point at the non-options
  489. that we previously skipped, so the caller will digest them. */
  490. if (first_nonopt != last_nonopt)
  491. optind = first_nonopt;
  492. return -1;
  493. }
  494. /* If we have come to a non-option and did not permute it,
  495. either stop the scan or describe it to the caller and pass it by. */
  496. if (NONOPTION_P)
  497. {
  498. if (ordering == REQUIRE_ORDER)
  499. return -1;
  500. optarg = argv[optind++];
  501. return 1;
  502. }
  503. /* We have found another option-ARGV-element.
  504. Skip the initial punctuation. */
  505. nextchar = (argv[optind] + 1
  506. + (longopts != NULL && argv[optind][1] == '-'));
  507. }
  508. /* Decode the current option-ARGV-element. */
  509. /* Check whether the ARGV-element is a long option.
  510. If long_only and the ARGV-element has the form "-f", where f is
  511. a valid short option, don't consider it an abbreviated form of
  512. a long option that starts with f. Otherwise there would be no
  513. way to give the -f short option.
  514. On the other hand, if there's a long option "fubar" and
  515. the ARGV-element is "-fu", do consider that an abbreviation of
  516. the long option, just like "--fu", and not "-f" with arg "u".
  517. This distinction seems to be the most useful approach. */
  518. if (longopts != NULL
  519. && (argv[optind][1] == '-'
  520. || (long_only && (argv[optind][2] || !my_index (optstring, argv[optind][1])))))
  521. {
  522. char *nameend;
  523. const struct option *p;
  524. const struct option *pfound = NULL;
  525. int exact = 0;
  526. int ambig = 0;
  527. int indfound = -1;
  528. int option_index;
  529. for (nameend = nextchar; *nameend && *nameend != '='; nameend++)
  530. /* Do nothing. */ ;
  531. /* Test all long options for either exact match
  532. or abbreviated matches. */
  533. for (p = longopts, option_index = 0; p->name; p++, option_index++)
  534. if (!strncmp (p->name, nextchar, nameend - nextchar))
  535. {
  536. if ((unsigned int) (nameend - nextchar)
  537. == (unsigned int) strlen (p->name))
  538. {
  539. /* Exact match found. */
  540. pfound = p;
  541. indfound = option_index;
  542. exact = 1;
  543. break;
  544. }
  545. else if (pfound == NULL)
  546. {
  547. /* First nonexact match found. */
  548. pfound = p;
  549. indfound = option_index;
  550. }
  551. else if (long_only
  552. || pfound->has_arg != p->has_arg
  553. || pfound->flag != p->flag
  554. || pfound->val != p->val)
  555. /* Second or later nonexact match found. */
  556. ambig = 1;
  557. }
  558. if (ambig && !exact)
  559. {
  560. if (print_errors)
  561. fprintf (stderr, _("%s: option `%s' is ambiguous\n"),
  562. argv[0], argv[optind]);
  563. nextchar += strlen (nextchar);
  564. optind++;
  565. optopt = 0;
  566. return '?';
  567. }
  568. if (pfound != NULL)
  569. {
  570. option_index = indfound;
  571. optind++;
  572. if (*nameend)
  573. {
  574. /* Don't test has_arg with >, because some C compilers don't
  575. allow it to be used on enums. */
  576. if (pfound->has_arg)
  577. optarg = nameend + 1;
  578. else
  579. {
  580. if (print_errors)
  581. {
  582. if (argv[optind - 1][1] == '-')
  583. /* --option */
  584. fprintf (stderr,
  585. _("%s: option `--%s' doesn't allow an argument\n"),
  586. argv[0], pfound->name);
  587. else
  588. /* +option or -option */
  589. fprintf (stderr,
  590. _("%s: option `%c%s' doesn't allow an argument\n"),
  591. argv[0], argv[optind - 1][0], pfound->name);
  592. }
  593. nextchar += strlen (nextchar);
  594. optopt = pfound->val;
  595. return '?';
  596. }
  597. }
  598. else if (pfound->has_arg == 1)
  599. {
  600. if (optind < argc)
  601. optarg = argv[optind++];
  602. else
  603. {
  604. if (print_errors)
  605. fprintf (stderr,
  606. _("%s: option `%s' requires an argument\n"),
  607. argv[0], argv[optind - 1]);
  608. nextchar += strlen (nextchar);
  609. optopt = pfound->val;
  610. return optstring[0] == ':' ? ':' : '?';
  611. }
  612. }
  613. nextchar += strlen (nextchar);
  614. if (longind != NULL)
  615. *longind = option_index;
  616. if (pfound->flag)
  617. {
  618. *(pfound->flag) = pfound->val;
  619. return 0;
  620. }
  621. return pfound->val;
  622. }
  623. /* Can't find it as a long option. If this is not getopt_long_only,
  624. or the option starts with '--' or is not a valid short
  625. option, then it's an error.
  626. Otherwise interpret it as a short option. */
  627. if (!long_only || argv[optind][1] == '-'
  628. || my_index (optstring, *nextchar) == NULL)
  629. {
  630. if (print_errors)
  631. {
  632. if (argv[optind][1] == '-')
  633. /* --option */
  634. fprintf (stderr, _("%s: unrecognized option `--%s'\n"),
  635. argv[0], nextchar);
  636. else
  637. /* +option or -option */
  638. fprintf (stderr, _("%s: unrecognized option `%c%s'\n"),
  639. argv[0], argv[optind][0], nextchar);
  640. }
  641. nextchar = (char *) "";
  642. optind++;
  643. optopt = 0;
  644. return '?';
  645. }
  646. }
  647. /* Look at and handle the next short option-character. */
  648. {
  649. char c = *nextchar++;
  650. char *temp = my_index (optstring, c);
  651. /* Increment `optind' when we start to process its last character. */
  652. if (*nextchar == '\0')
  653. ++optind;
  654. if (temp == NULL || c == ':')
  655. {
  656. if (print_errors)
  657. {
  658. if (posixly_correct)
  659. /* 1003.2 specifies the format of this message. */
  660. fprintf (stderr, _("%s: illegal option -- %c\n"),
  661. argv[0], c);
  662. else
  663. fprintf (stderr, _("%s: invalid option -- %c\n"),
  664. argv[0], c);
  665. }
  666. optopt = c;
  667. return '?';
  668. }
  669. /* Convenience. Treat POSIX -W foo same as long option --foo */
  670. if (temp[0] == 'W' && temp[1] == ';')
  671. {
  672. char *nameend;
  673. const struct option *p;
  674. const struct option *pfound = NULL;
  675. int exact = 0;
  676. int ambig = 0;
  677. int indfound = 0;
  678. int option_index;
  679. /* This is an option that requires an argument. */
  680. if (*nextchar != '\0')
  681. {
  682. optarg = nextchar;
  683. /* If we end this ARGV-element by taking the rest as an arg,
  684. we must advance to the next element now. */
  685. optind++;
  686. }
  687. else if (optind == argc)
  688. {
  689. if (print_errors)
  690. {
  691. /* 1003.2 specifies the format of this message. */
  692. fprintf (stderr, _("%s: option requires an argument -- %c\n"),
  693. argv[0], c);
  694. }
  695. optopt = c;
  696. if (optstring[0] == ':')
  697. c = ':';
  698. else
  699. c = '?';
  700. return c;
  701. }
  702. else
  703. /* We already incremented `optind' once;
  704. increment it again when taking next ARGV-elt as argument. */
  705. optarg = argv[optind++];
  706. /* optarg is now the argument, see if it's in the
  707. table of longopts. */
  708. for (nextchar = nameend = optarg; *nameend && *nameend != '='; nameend++)
  709. /* Do nothing. */ ;
  710. /* Test all long options for either exact match
  711. or abbreviated matches. */
  712. for (p = longopts, option_index = 0; p->name; p++, option_index++)
  713. if (!strncmp (p->name, nextchar, nameend - nextchar))
  714. {
  715. if ((unsigned int) (nameend - nextchar) == strlen (p->name))
  716. {
  717. /* Exact match found. */
  718. pfound = p;
  719. indfound = option_index;
  720. exact = 1;
  721. break;
  722. }
  723. else if (pfound == NULL)
  724. {
  725. /* First nonexact match found. */
  726. pfound = p;
  727. indfound = option_index;
  728. }
  729. else
  730. /* Second or later nonexact match found. */
  731. ambig = 1;
  732. }
  733. if (ambig && !exact)
  734. {
  735. if (print_errors)
  736. fprintf (stderr, _("%s: option `-W %s' is ambiguous\n"),
  737. argv[0], argv[optind]);
  738. nextchar += strlen (nextchar);
  739. optind++;
  740. return '?';
  741. }
  742. if (pfound != NULL)
  743. {
  744. option_index = indfound;
  745. if (*nameend)
  746. {
  747. /* Don't test has_arg with >, because some C compilers don't
  748. allow it to be used on enums. */
  749. if (pfound->has_arg)
  750. optarg = nameend + 1;
  751. else
  752. {
  753. if (print_errors)
  754. fprintf (stderr, _("\
  755. %s: option `-W %s' doesn't allow an argument\n"),
  756. argv[0], pfound->name);
  757. nextchar += strlen (nextchar);
  758. return '?';
  759. }
  760. }
  761. else if (pfound->has_arg == 1)
  762. {
  763. if (optind < argc)
  764. optarg = argv[optind++];
  765. else
  766. {
  767. if (print_errors)
  768. fprintf (stderr,
  769. _("%s: option `%s' requires an argument\n"),
  770. argv[0], argv[optind - 1]);
  771. nextchar += strlen (nextchar);
  772. return optstring[0] == ':' ? ':' : '?';
  773. }
  774. }
  775. nextchar += strlen (nextchar);
  776. if (longind != NULL)
  777. *longind = option_index;
  778. if (pfound->flag)
  779. {
  780. *(pfound->flag) = pfound->val;
  781. return 0;
  782. }
  783. return pfound->val;
  784. }
  785. nextchar = NULL;
  786. return 'W'; /* Let the application handle it. */
  787. }
  788. if (temp[1] == ':')
  789. {
  790. if (temp[2] == ':')
  791. {
  792. /* This is an option that accepts an argument optionally. */
  793. if (*nextchar != '\0')
  794. {
  795. optarg = nextchar;
  796. optind++;
  797. }
  798. else
  799. optarg = NULL;
  800. nextchar = NULL;
  801. }
  802. else
  803. {
  804. /* This is an option that requires an argument. */
  805. if (*nextchar != '\0')
  806. {
  807. optarg = nextchar;
  808. /* If we end this ARGV-element by taking the rest as an arg,
  809. we must advance to the next element now. */
  810. optind++;
  811. }
  812. else if (optind == argc)
  813. {
  814. if (print_errors)
  815. {
  816. /* 1003.2 specifies the format of this message. */
  817. fprintf (stderr,
  818. _("%s: option requires an argument -- %c\n"),
  819. argv[0], c);
  820. }
  821. optopt = c;
  822. if (optstring[0] == ':')
  823. c = ':';
  824. else
  825. c = '?';
  826. }
  827. else
  828. /* We already incremented `optind' once;
  829. increment it again when taking next ARGV-elt as argument. */
  830. optarg = argv[optind++];
  831. nextchar = NULL;
  832. }
  833. }
  834. return c;
  835. }
  836. }
  837. int
  838. getopt (argc, argv, optstring)
  839. int argc;
  840. char *const *argv;
  841. const char *optstring;
  842. {
  843. return _getopt_internal (argc, argv, optstring,
  844. (const struct option *) 0,
  845. (int *) 0,
  846. 0);
  847. }
  848. #endif /* Not ELIDE_CODE. */
  849. #ifdef TEST
  850. /* Compile with -DTEST to make an executable for use in testing
  851. the above definition of `getopt'. */
  852. int
  853. main (argc, argv)
  854. int argc;
  855. char **argv;
  856. {
  857. int c;
  858. int digit_optind = 0;
  859. while (1)
  860. {
  861. int this_option_optind = optind ? optind : 1;
  862. c = getopt (argc, argv, "abc:d:0123456789");
  863. if (c == -1)
  864. break;
  865. switch (c)
  866. {
  867. case '0':
  868. case '1':
  869. case '2':
  870. case '3':
  871. case '4':
  872. case '5':
  873. case '6':
  874. case '7':
  875. case '8':
  876. case '9':
  877. if (digit_optind != 0 && digit_optind != this_option_optind)
  878. printf ("digits occur in two different argv-elements.\n");
  879. digit_optind = this_option_optind;
  880. printf ("option %c\n", c);
  881. break;
  882. case 'a':
  883. printf ("option a\n");
  884. break;
  885. case 'b':
  886. printf ("option b\n");
  887. break;
  888. case 'c':
  889. printf ("option c with value `%s'\n", optarg);
  890. break;
  891. case '?':
  892. break;
  893. default:
  894. printf ("?? getopt returned character code 0%o ??\n", c);
  895. }
  896. }
  897. if (optind < argc)
  898. {
  899. printf ("non-option ARGV-elements: ");
  900. while (optind < argc)
  901. printf ("%s ", argv[optind++]);
  902. printf ("\n");
  903. }
  904. exit (0);
  905. }
  906. #endif /* TEST */