29

I'm not sure how to correctly use optstring in the getopt function in C.

How should that string be formatted? I saw examples where letters are next to each other, sometimes separated by a semicolon, sometimes by two semicolons.

What does it mean?

Lightness Races in Orbit
  • 378,754
  • 76
  • 643
  • 1,055
bLAZ
  • 1,689
  • 4
  • 19
  • 31

3 Answers3

39

It is just a string, and each character of this string represents an option. If this option requires an argument, you have to follow the option character by :.

For example, "cdf:g" accepts the options c, d, f, and g; f requires an additional argument.

An option in command line looks like -option, so you can use the options -c, -d, -f argument and -g.

S.S. Anne
  • 15,171
  • 8
  • 38
  • 76
md5
  • 23,373
  • 3
  • 44
  • 93
  • And then in command line options have dash and are separated with space? And if some option is with `:` then in command line the following typed input after space is taken as argument? – bLAZ Nov 06 '12 at 13:11
  • Now I understand it:) Thank you! – bLAZ Nov 06 '12 at 13:15
  • 3
    When the option has an argument, the value is found in the (global) variable `optarg` that's declared in the header where [`getopt()`](http://pubs.opengroup.org/onlinepubs/9699919799/functions/getopt.html) is declared (``). Two colons is an extension that indicates the following argument is optional. – Jonathan Leffler Nov 06 '12 at 14:40
13

The getopt(3) manpage makes it pretty clear :

  • the string itself is used for specifying the legal options that can appear on the commandline,
  • if the option is followed by a :, then that option has a required parameter - not specifying it will cause the function to fail,
  • if the option is followed by a ::, then that option has an optional parameter.

The options are one-letter identifiers. For example, specifying a string like aB:cD:: as the optstring will mean that your program takes options a, B with a required parameter, c, and D with an optional parameter.

Daniel Kamil Kozar
  • 18,476
  • 5
  • 50
  • 64
4

If colon :is followed by a char or string means this option must require the argument and if there are no colon means no arguments

for more details do man 3 getopt or visit the link or manpage

Omkant
  • 9,018
  • 8
  • 39
  • 59
  • 5
    It should be if a character is followed by `:`.? – sjsam Jul 11 '16 at 16:01
  • According to [getopt manual](https://pubs.opengroup.org/onlinepubs/000095399/functions/getopt.html): "The argument optstring is a string of recognized option characters; if a character is followed by a colon, the option takes an argument." – aurelia Sep 05 '21 at 16:03