GNU long option command line parsing getopt_long ()

Source: Internet
Author: User

Original article link

In 1990s, UNIX applications began to support long options, that is, a pair of short dashes, a descriptive option name, and a parameter that uses equal signs to connect to options.
GNU provides the getopt-long () and getopt-long-only () functions to support command line parsing of long options. The latter's long option string starts with a short horizontal line, instead of a pair of dashes.

Getopt_long () is a getopt () version that supports both long and short options. Their declaration is as follows:

# I nclude <getopt. h>

Int getopt_long (int argc, char * const argv [], const char * optstring, const struct option * longopts, int * longindex );

Int getopt_long_only (int argc, char * const argv [], const char * optstring, const struct option * longopts, int * longindex );
The first three parameters of getopt_long () are the same as those of getopt (). The first three parameters are an array pointing to the option structure. The option structure is called a "long option table ". If the longindex parameter is not set to NULL, it points to a variable, which is assigned the index value of the long option in longopts, which can be used for error diagnosis.

The Declaration of the option structure in getopt. h is as follows:

Struct option {
Const char * name;
Int has_arg;
Int * flag;
Int val;
};
The elements in the structure are described as follows:

Const char * name

This is the option name, with no Dash in front. For example, "help" and "verbose.
Int has_arg

Specifies whether option parameters are available. If yes, which type of parameter is used, its value must be one of the following tables.
Symbol constant numerical meaning
The no_argument0 option has no parameters.
Parameters required for the required_argument1 Option
Optional optional_argument2 option Parameter
Int * flag

If the pointer is NULL, getopt_long () returns the value in the val field of the structure. If the pointer is not NULL, getopt_long () will fill in the value in the val field in the variable to which it points, and getopt_long () will return 0. If the flag is not NULL but no long option is found, the value of the variable to which it points remains unchanged.
Int val

This value is the returned value when the long option is found, or the value in * flag is loaded when the flag is not NULL. In typical cases, if the flag is not NULL, val is a real/false value, such as 1 or 0. If the flag is NULL, val is usually a character constant, if the length option is the same as the short option, the character constant should be the same as the parameter of this option in optstring.
Each long option has a separate entry in the long option table, which must be filled with the correct value. The value of the last element in the array should be all 0. Arrays do not need to be sorted. getopt_long () performs linear search. However, sorting by long names makes it easier for programmers to read.

The usage of the flag and val mentioned above seems a bit confusing, but they are very useful, so it is necessary to thoroughly understand them.

Most of the time, programmers will set some tag variables during option Processing Based on the options found by getopt_long (). For example, when getopt () is used, the following program format is often made:

Int do_name, do_gf_name, do_love;/* mark variable */char * B _opt_arg; while (c = getopt (argc, argv, ": ngl :"))! =-1) {switch (c) {case 'N': do_name = 1; case 'G': do_gf_name = 1; break; case 'l ': B _opt_arg = optarg ;...... }}

 

When the flag is not NULL, getopt_long * () will set the flag variable for you. That is to say, in the above Code, the processing of the options 'N' and 'L' is only set some tags. If the flag is not NULL, getopt_long () the tag variable corresponding to each option can be automatically set, so that the two conditions in the preceding switch statement can be reduced to one. The following is an example of a long option table and corresponding processing code.

Listing 5:

1 # I nclude <stdio. h> 2 # I nclude <getopt. h> 3 4 int do_name, do_gf_name; 5 char * l_opt_arg; 6 7 struct option longopts [] = {8 {"name", no_argument, & do_name, 1 }, 9 {"gf_name", no_argument, & do_gf_name, 1}, 10 {"love", required_argument, NULL, 'L'}, 11 {0, 0, 0, 0 }, 12}; 13 14 int main (int argc, char * argv []) 15 {16 int c; 17 18 while (c = getopt_long (argc, argv, ": l: ", longopts, NULL ))! =-1) {19 switch (c) {20 case 'l': 21 l_opt_arg = optarg; 22 printf ("Our love is % s! \ N ", l_opt_arg); 23 break; 24 case 0: 25 printf (" getopt_long () Setting variable: do_name = % d \ n ", do_name); 26 printf (" getopt_long () set variable: do_gf_name = % d \ n ", do_gf_name); 27 break; 28} 29} 30 return 0; 31}

 

Before testing, let's review the pointer flag in the option structure.

If the pointer is NULL, getopt_long () returns the value in the val field of the structure. If the pointer is not NULL, getopt_long () will fill in the value in the val field in the variable to which it points, and getopt_long () will return 0. If the flag is not NULL but no long option is found, the value of the variable to which it points remains unchanged.
The following is a test:

$./Long_opt_demo -- name
Getopt_long () variable: do_name = 1
Getopt_long () variable: do_gf_name = 0

$./Long_opt_demo -- gf_name
Getopt_long () variable: do_name = 0
Getopt_long () variable: do_gf_name = 1

$./Long_opt_demo -- love forever
Our love is forever!

$./Long_opt_demo-l forever
Our love is forever!
After the test, you should be touched. So far, we have discussed flag and val. The following summarizes the meanings of various return values of get_long:

The returned value is ambiguous.

  • 0 getopt_long () sets a flag. Its value is the same as the value of the val field in the option structure.
  • 1 optarg records a command line parameter.
  • '? 'Invalid Option
  • ':' Option parameter missing
  • 'X' option character 'X'
  • -1 option resolution ended

From a practical point of view, we expect each long option to correspond to a short option. In this case, in the option structure, as long as the flag is set to NULL, set val to the short option character corresponding to the long option. For example, the program in listing 5 is modified as follows.

Listing 6:

 1 #i nclude <stdio.h> 2 #i nclude <getopt.h> 3  4 int do_name, do_gf_name; 5 char *l_opt_arg; 6  7 struct option longopts[] = { 8      { "name",         no_argument,             NULL,                 'n'     }, 9      { "gf_name",     no_argument,             NULL,                 'g'     },10      { "love",         required_argument,     NULL,                 'l'     },11      {      0,     0,     0,     0},12 };13 14 int main(int argc, char *argv[])15 {16      int c;17     18      while((c = getopt_long(argc, argv, ":l:", longopts, NULL)) != -1){19          switch (c){20          case 'n':21              printf("My name is LYR.\n");22              break;23          case 'g':24              printf("Her name is BX.\n");25              break;26          case 'l':27              l_opt_arg = optarg;28              printf("Our love is %s!\n", l_opt_arg);29              break;30          }31      }32      return 0;33 }

 

The test results are as follows:

$./Long_opt_demo -- name -- gf_name -- love forever
My name is LYR.
Her name is BX.
Our love is forever!

$./Long_opt_demo-ng-l forever
My name is LYR.
Her name is BX.
Our love is forever!
9. Use GNU getopt () or getopt_long () on a platform other than LINUX ()

Copy the source file (http://sourceware.org/glibc/) from the CVS file of the GNU program or gnu c Library (GLIBC ). The source files are getopt. h, getopt. c, and getoptl. c. include these files in your project. In addition, the best COPYING. LIB file in your project is included, because the content of gnu lgpl (GNU Library Public License) is included in all the files named COPYING. LIB.
10. Conclusion

The program needs to be able to quickly process various options and parameters without wasting too much time on developers. In this regard, both GUI (graphical user interaction) Programs and CUI (command line interaction) programs are their primary tasks. The difference lies only in the different implementation methods. GUI interacts with each other through graphical controls such as menus and dialogs, while CUI uses plain text interaction. In program development, CUI is the preferred solution for many testing programs.
The getopt () function is a standard library call that allows you to use direct while/switch statements to conveniently process command line parameters and check options (with or without additional parameters) one by one ). Similar to getopt_long (), getopt_long () allows more descriptive long options to be processed without additional work, which is very popular among developers.

End

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.