Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to specify an optstring in the getopt function?

Tags:

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?

like image 407
bLAZ Avatar asked Nov 06 '12 13:11

bLAZ


People also ask

What is Optstring in getopt?

According to getopt manual: "The argument optstring is a string of recognized option characters; if a character is followed by a colon, the option takes an argument."

Does getopt modify argv?

(The -W option is reserved by POSIX. 2 for implementation extensions.) This behavior is a GNU extension, not available with libraries before glibc 2. By default, getopt() permutes the contents of argv as it scans, so that eventually all the nonoptions are at the end.

What do the colons mean in getopt?

An option character in this string can be followed by a colon (' : ') to indicate that it takes a required argument. If an option character is followed by two colons (' :: '), its argument is optional; this is a GNU extension. getopt has three ways to deal with options that follow non-options argv elements.

What is Optind in getopt?

The variable optind is the index of the next element of argv to be processed. It is initialized to 1, and getopt() updates it as it processes each element of argv[]. The getopt() function returns the next option character (if one is found) from argv that matches a character in optstring, if any.


1 Answers

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.

like image 172
md5 Avatar answered Oct 25 '22 22:10

md5