Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

getopt does not parse optional arguments to parameters

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; } 
like image 958
hayalci Avatar asked Jun 27 '09 12:06

hayalci


People also ask

What does getopt do 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.

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 does the getopt function return when there is no more work to do?

The getopt function returns the option character for the next command line option. When no more option arguments are available, it returns -1 .

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 (:).


1 Answers

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! 
like image 136
hayalci Avatar answered Sep 18 '22 18:09

hayalci