getopt.texi 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352
  1. @node Getopt, Argp, , Parsing Program Arguments
  2. @section Parsing program options using @code{getopt}
  3. The @code{getopt} and @code{getopt_long} functions automate some of the
  4. chore involved in parsing typical unix command line options.
  5. @menu
  6. * Using Getopt:: Using the @code{getopt} function.
  7. * Example of Getopt:: An example of parsing options with @code{getopt}.
  8. * Getopt Long Options:: GNU suggests utilities accept long-named
  9. options; here is one way to do.
  10. * Getopt Long Option Example:: An example of using @code{getopt_long}.
  11. @end menu
  12. @node Using Getopt, Example of Getopt, , Getopt
  13. @subsection Using the @code{getopt} function
  14. Here are the details about how to call the @code{getopt} function. To
  15. use this facility, your program must include the header file
  16. @file{unistd.h}.
  17. @pindex unistd.h
  18. @deftypevar int opterr
  19. @standards{POSIX.2, unistd.h}
  20. If the value of this variable is nonzero, then @code{getopt} prints an
  21. error message to the standard error stream if it encounters an unknown
  22. option character or an option with a missing required argument. This is
  23. the default behavior. If you set this variable to zero, @code{getopt}
  24. does not print any messages, but it still returns the character @code{?}
  25. to indicate an error.
  26. @end deftypevar
  27. @deftypevar int optopt
  28. @standards{POSIX.2, unistd.h}
  29. When @code{getopt} encounters an unknown option character or an option
  30. with a missing required argument, it stores that option character in
  31. this variable. You can use this for providing your own diagnostic
  32. messages.
  33. @end deftypevar
  34. @deftypevar int optind
  35. @standards{POSIX.2, unistd.h}
  36. This variable is set by @code{getopt} to the index of the next element
  37. of the @var{argv} array to be processed. Once @code{getopt} has found
  38. all of the option arguments, you can use this variable to determine
  39. where the remaining non-option arguments begin. The initial value of
  40. this variable is @code{1}.
  41. @end deftypevar
  42. @deftypevar {char *} optarg
  43. @standards{POSIX.2, unistd.h}
  44. This variable is set by @code{getopt} to point at the value of the
  45. option argument, for those options that accept arguments.
  46. @end deftypevar
  47. @deftypefun int getopt (int @var{argc}, char *const *@var{argv}, const char *@var{options})
  48. @standards{POSIX.2, unistd.h}
  49. @safety{@prelim{}@mtunsafe{@mtasurace{:getopt} @mtsenv{}}@asunsafe{@ascuheap{} @ascuintl{} @asulock{} @asucorrupt{}}@acunsafe{@acsmem{} @aculock{} @acucorrupt{}}}
  50. @c Swapping elements of passed-in argv may be partial in case of
  51. @c cancellation. Gettext brings about a whole lot of AS and AC safety
  52. @c issues. The getopt API involves returning values in the
  53. @c non-thread-specific optarg variable, which adds another thread-safety
  54. @c issue. Given print_errors, it may output errors to stderr, which may
  55. @c self-deadlock, leak locks, or encounter (in a signal handler) or
  56. @c leave (in case of cancellation) stderr in an inconsistent state.
  57. @c Various implicit, indirect uses of malloc, in uses of memstream and
  58. @c asprintf for error-printing, bring about the usual malloc issues.
  59. @c
  60. @c _getopt_internal
  61. @c _getopt_internal_r
  62. @c gettext
  63. @c _getopt_initialize
  64. @c getenv
  65. @c open_memstream
  66. @c lockfile, unlockfile, __fxprintf -> stderr
  67. @c asprintf
  68. The @code{getopt} function gets the next option argument from the
  69. argument list specified by the @var{argv} and @var{argc} arguments.
  70. Normally these values come directly from the arguments received by
  71. @code{main}.
  72. The @var{options} argument is a string that specifies the option
  73. characters that are valid for this program. An option character in this
  74. string can be followed by a colon (@samp{:}) to indicate that it takes a
  75. required argument. If an option character is followed by two colons
  76. (@samp{::}), its argument is optional; this is a GNU extension.
  77. @code{getopt} has three ways to deal with options that follow
  78. non-options @var{argv} elements. The special argument @samp{--} forces
  79. in all cases the end of option scanning.
  80. @itemize @bullet
  81. @item
  82. The default is to permute the contents of @var{argv} while scanning it
  83. so that eventually all the non-options are at the end. This allows
  84. options to be given in any order, even with programs that were not
  85. written to expect this.
  86. @item
  87. If the @var{options} argument string begins with a hyphen (@samp{-}), this
  88. is treated specially. It permits arguments that are not options to be
  89. returned as if they were associated with option character @samp{\1}.
  90. @item
  91. POSIX demands the following behavior: the first non-option stops option
  92. processing. This mode is selected by either setting the environment
  93. variable @code{POSIXLY_CORRECT} or beginning the @var{options} argument
  94. string with a plus sign (@samp{+}).
  95. @end itemize
  96. The @code{getopt} function returns the option character for the next
  97. command line option. When no more option arguments are available, it
  98. returns @code{-1}. There may still be more non-option arguments; you
  99. must compare the external variable @code{optind} against the @var{argc}
  100. parameter to check this.
  101. If the option has an argument, @code{getopt} returns the argument by
  102. storing it in the variable @var{optarg}. You don't ordinarily need to
  103. copy the @code{optarg} string, since it is a pointer into the original
  104. @var{argv} array, not into a static area that might be overwritten.
  105. If @code{getopt} finds an option character in @var{argv} that was not
  106. included in @var{options}, or a missing option argument, it returns
  107. @samp{?} and sets the external variable @code{optopt} to the actual
  108. option character. If the first character of @var{options} is a colon
  109. (@samp{:}), then @code{getopt} returns @samp{:} instead of @samp{?} to
  110. indicate a missing option argument. In addition, if the external
  111. variable @code{opterr} is nonzero (which is the default), @code{getopt}
  112. prints an error message.
  113. @end deftypefun
  114. @node Example of Getopt
  115. @subsection Example of Parsing Arguments with @code{getopt}
  116. Here is an example showing how @code{getopt} is typically used. The
  117. key points to notice are:
  118. @itemize @bullet
  119. @item
  120. Normally, @code{getopt} is called in a loop. When @code{getopt} returns
  121. @code{-1}, indicating no more options are present, the loop terminates.
  122. @item
  123. A @code{switch} statement is used to dispatch on the return value from
  124. @code{getopt}. In typical use, each case just sets a variable that
  125. is used later in the program.
  126. @item
  127. A second loop is used to process the remaining non-option arguments.
  128. @end itemize
  129. @smallexample
  130. @include testopt.c.texi
  131. @end smallexample
  132. Here are some examples showing what this program prints with different
  133. combinations of arguments:
  134. @smallexample
  135. % testopt
  136. aflag = 0, bflag = 0, cvalue = (null)
  137. % testopt -a -b
  138. aflag = 1, bflag = 1, cvalue = (null)
  139. % testopt -ab
  140. aflag = 1, bflag = 1, cvalue = (null)
  141. % testopt -c foo
  142. aflag = 0, bflag = 0, cvalue = foo
  143. % testopt -cfoo
  144. aflag = 0, bflag = 0, cvalue = foo
  145. % testopt arg1
  146. aflag = 0, bflag = 0, cvalue = (null)
  147. Non-option argument arg1
  148. % testopt -a arg1
  149. aflag = 1, bflag = 0, cvalue = (null)
  150. Non-option argument arg1
  151. % testopt -c foo arg1
  152. aflag = 0, bflag = 0, cvalue = foo
  153. Non-option argument arg1
  154. % testopt -a -- -b
  155. aflag = 1, bflag = 0, cvalue = (null)
  156. Non-option argument -b
  157. % testopt -a -
  158. aflag = 1, bflag = 0, cvalue = (null)
  159. Non-option argument -
  160. @end smallexample
  161. @node Getopt Long Options
  162. @subsection Parsing Long Options with @code{getopt_long}
  163. To accept GNU-style long options as well as single-character options,
  164. use @code{getopt_long} instead of @code{getopt}. This function is
  165. declared in @file{getopt.h}, not @file{unistd.h}. You should make every
  166. program accept long options if it uses any options, for this takes
  167. little extra work and helps beginners remember how to use the program.
  168. @deftp {Data Type} {struct option}
  169. @standards{GNU, getopt.h}
  170. This structure describes a single long option name for the sake of
  171. @code{getopt_long}. The argument @var{longopts} must be an array of
  172. these structures, one for each long option. Terminate the array with an
  173. element containing all zeros.
  174. The @code{struct option} structure has these fields:
  175. @table @code
  176. @item const char *name
  177. This field is the name of the option. It is a string.
  178. @item int has_arg
  179. This field says whether the option takes an argument. It is an integer,
  180. and there are three legitimate values: @w{@code{no_argument}},
  181. @code{required_argument} and @code{optional_argument}.
  182. @item int *flag
  183. @itemx int val
  184. These fields control how to report or act on the option when it occurs.
  185. If @code{flag} is a null pointer, then the @code{val} is a value which
  186. identifies this option. Often these values are chosen to uniquely
  187. identify particular long options.
  188. If @code{flag} is not a null pointer, it should be the address of an
  189. @code{int} variable which is the flag for this option. The value in
  190. @code{val} is the value to store in the flag to indicate that the option
  191. was seen.
  192. @end table
  193. @end deftp
  194. @deftypefun int getopt_long (int @var{argc}, char *const *@var{argv}, const char *@var{shortopts}, const struct option *@var{longopts}, int *@var{indexptr})
  195. @standards{GNU, getopt.h}
  196. @safety{@prelim{}@mtunsafe{@mtasurace{:getopt} @mtsenv{}}@asunsafe{@ascuheap{} @ascuintl{} @asulock{} @asucorrupt{}}@acunsafe{@acsmem{} @aculock{} @acucorrupt{}}}
  197. @c Same issues as getopt.
  198. Decode options from the vector @var{argv} (whose length is @var{argc}).
  199. The argument @var{shortopts} describes the short options to accept, just as
  200. it does in @code{getopt}. The argument @var{longopts} describes the long
  201. options to accept (see above).
  202. When @code{getopt_long} encounters a short option, it does the same
  203. thing that @code{getopt} would do: it returns the character code for the
  204. option, and stores the option's argument (if it has one) in @code{optarg}.
  205. When @code{getopt_long} encounters a long option, it takes actions based
  206. on the @code{flag} and @code{val} fields of the definition of that
  207. option. The option name may be abbreviated as long as the abbreviation is
  208. unique.
  209. If @code{flag} is a null pointer, then @code{getopt_long} returns the
  210. contents of @code{val} to indicate which option it found. You should
  211. arrange distinct values in the @code{val} field for options with
  212. different meanings, so you can decode these values after
  213. @code{getopt_long} returns. If the long option is equivalent to a short
  214. option, you can use the short option's character code in @code{val}.
  215. If @code{flag} is not a null pointer, that means this option should just
  216. set a flag in the program. The flag is a variable of type @code{int}
  217. that you define. Put the address of the flag in the @code{flag} field.
  218. Put in the @code{val} field the value you would like this option to
  219. store in the flag. In this case, @code{getopt_long} returns @code{0}.
  220. For any long option, @code{getopt_long} tells you the index in the array
  221. @var{longopts} of the options definition, by storing it into
  222. @code{*@var{indexptr}}. You can get the name of the option with
  223. @code{@var{longopts}[*@var{indexptr}].name}. So you can distinguish among
  224. long options either by the values in their @code{val} fields or by their
  225. indices. You can also distinguish in this way among long options that
  226. set flags.
  227. When a long option has an argument, @code{getopt_long} puts the argument
  228. value in the variable @code{optarg} before returning. When the option
  229. has no argument, the value in @code{optarg} is a null pointer. This is
  230. how you can tell whether an optional argument was supplied.
  231. When @code{getopt_long} has no more options to handle, it returns
  232. @code{-1}, and leaves in the variable @code{optind} the index in
  233. @var{argv} of the next remaining argument.
  234. @end deftypefun
  235. Since long option names were used before @code{getopt_long}
  236. was invented there are program interfaces which require programs
  237. to recognize options like @w{@samp{-option value}} instead of
  238. @w{@samp{--option value}}. To enable these programs to use the GNU
  239. getopt functionality there is one more function available.
  240. @deftypefun int getopt_long_only (int @var{argc}, char *const *@var{argv}, const char *@var{shortopts}, const struct option *@var{longopts}, int *@var{indexptr})
  241. @standards{GNU, getopt.h}
  242. @safety{@prelim{}@mtunsafe{@mtasurace{:getopt} @mtsenv{}}@asunsafe{@ascuheap{} @ascuintl{} @asulock{} @asucorrupt{}}@acunsafe{@acsmem{} @aculock{} @acucorrupt{}}}
  243. @c Same issues as getopt.
  244. The @code{getopt_long_only} function is equivalent to the
  245. @code{getopt_long} function but it allows the user of the
  246. application to pass long options with only @samp{-} instead of
  247. @samp{--}. The @samp{--} prefix is still recognized but instead of
  248. looking through the short options if a @samp{-} is seen it is first
  249. tried whether this parameter names a long option. If not, it is parsed
  250. as a short option. In case both short and long options could be
  251. matched (this can happen with single letter long options), the short
  252. option is preferred (with some caveats). For long options,
  253. abbreviations are detected as well.
  254. Assuming @code{getopt_long_only} is used starting an application with
  255. @smallexample
  256. app -foo
  257. @end smallexample
  258. @noindent
  259. the @code{getopt_long_only} will first look for a long option named
  260. @samp{foo}. If this is not found, the short options @samp{f}, @samp{o},
  261. and again @samp{o} are recognized.
  262. It gets more interesting with single letter long options. If we
  263. define options in the following way
  264. @smallexample
  265. static struct option long_options[] = @{
  266. @{"f", no_argument, 0, 0 @},
  267. @{"foo", no_argument, 0, 0 @},
  268. @{0, 0, 0, 0 @},
  269. @};
  270. @end smallexample
  271. @noindent
  272. use @code{"f"} (as a C string) as an option string and start the
  273. application with @option{-f}, the short option will be matched.
  274. @option{--f} will match the long one. And both @option{-fo} and
  275. @option{-foo} will match the long option @code{"foo"}.
  276. Be aware that if the option string would be @code{"f:"} (thus the
  277. short option requires an argument), using just @option{-f} leads to an
  278. error. But using @option{-fo} results in the long option being
  279. matched. For passing an argument in this situation, you need to do it
  280. as two arguments (@option{-f}, @option{o}). Though any other value
  281. would work in a single argument (e.g., @option{-f1}), since it would
  282. not match a long option (or its abbreviation).
  283. @end deftypefun
  284. @node Getopt Long Option Example
  285. @subsection Example of Parsing Long Options with @code{getopt_long}
  286. @smallexample
  287. @include longopt.c.texi
  288. @end smallexample