In C, getopt_long does not parse the optional arguments to command line parameters parameters.
When I run the program, the optional argument is not recognized like the example run below.
$ ./respond --praise John Kudos to John $ ./respond --blame John You suck ! $ ./respond --blame You suck !
Here is the test code.
#include <stdio.h> #include <getopt.h> int main(int argc, char ** argv ) { int getopt_ret, option_index; static struct option long_options[] = { {"praise", required_argument, 0, 'p'}, {"blame", optional_argument, 0, 'b'}, {0, 0, 0, 0} }; while (1) { getopt_ret = getopt_long( argc, argv, "p:b::", long_options, &option_index); if (getopt_ret == -1) break; switch(getopt_ret) { case 0: break; case 'p': printf("Kudos to %s\n", optarg); break; case 'b': printf("You suck "); if (optarg) printf (", %s!\n", optarg); else printf ("!\n", optarg); break; case '?': printf("Unknown option\n"); break; } } return 0; }
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.
(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.
The getopt function returns the option character for the next command line option. When no more option arguments are available, it returns -1 .
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 (:).
Although not mentioned in glibc documentation or getopt man page, optional arguments to long style command line parameters require 'equals sign' (=). Space separating the optional argument from the parameter does not work.
An example run with the test code:
$ ./respond --praise John Kudos to John $ ./respond --praise=John Kudos to John $ ./respond --blame John You suck ! $ ./respond --blame=John You suck , John!
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