Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mandatory options with getopt_long() in C

Tags:

c

getopt-long

With C/ C++, getopt_long() can be used to parse command line arguments. Is it possible to tell the function that some of the options are mandatory? For example, how can I tell getopt_long that the parsing should give error if startServer is called without mentioning the port below?

./startServer -port 80

Note: I am not talking of option arguments as mandatory but rather the options themselves.

like image 689
Jaywalker Avatar asked Jan 12 '11 12:01

Jaywalker


People also ask

What is Getopt_long in C?

The getopt() function is a builtin function in C and is used to parse command line arguments. Syntax: getopt(int argc, char *const argv[], const char *optstring) optstring is simply a list of characters, each representing a single character option.

What does getopt return?

RETURN VALUE The getopt() function returns the next option character specified on the command line. A colon (:) is returned if getopt() detects a missing argument and the first character of optstring was a colon (:).

What is Optarg getopt?

optarg indicates an optional parameter to a command line option. opterr can be set to 0 to prevent getopt() from printing error messages. optind is the index of the next element of the argument list to be process, and optopt is the command line option last matched.

What is getopt H?

11.17 getopt. h. Defines the type struct option and declares the variables optarg , optind , opterr , optopt and the functions getopt , getopt_long , getopt_long_only .


1 Answers

getopt_long() is not part of the C language. It is a GNU invention which is available in some C implementations, but far from all.

The version of getopt_long() in glibc (used in most Linux distributions) does not allow you to specify that an option is mandatory. You'll have to check them explicitly after you're done parsing the command line.

like image 61
DES Avatar answered Oct 01 '22 12:10

DES