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.
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.
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 (:).
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.
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 .
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With