Parse command line parameters in Linux (getopt_long usage)

Source: Internet
Author: User

Getopt_long supports command line parsing of Long Options. Use man getopt_long to get its declaration as follows:
# Include <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 );

Note: argc and argv in the function are usually transmitted directly from main () to two parameters. Optsting is a string composed of option parameters, such

If any letter in the string has a colon, this option requires a parameter. The next parameter is the pointer to the array, which is

The option structure array. The option structure is called the long option table. Its declaration 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: Option name, with no Dash in front. For example, "help" and "verbose.
Int has_arg: describes whether long options have option parameters. If so, the following table lists the types of parameters:
Symbol constant numerical meaning
No_argument 0 option no Parameter
Parameters required for the required_argument 1 option
Optional_argument 2 Option parameter is optional
Int * flag:
If the pointer is null, getopt_long returns the value of the Val field;
If the pointer is not null, the structure to which it points is filled with the value of the Val field, and getopt_long returns 0.
Int VAL:
If the flag is null, Val is usually a character constant. If the short option and long option are the same, the character should be in the optstring

The parameters of this option are the same;

The last parameter: longindex is generally null. If it is not set to null, it points to a variable.

The value is assigned to the index value of the long option in longopts, which can be used for error diagnosis.

Note: The getopt-long () and getopt-long-only () functions provided by GNU start with a short horizontal line.

Instead of a pair of dashes.

Linux Command Line Conventions:
Almost all GNU/Linux programs follow some command line parameter definitions. The expected parameters of the program can be divided into two types:

Options or flags and other types of parameters. Options modifies the way the program runs, while other types of parameters provide

(For example, the name of the input file ).

You can use either of the following methods for options:
1) short options: Short parameters, as the name suggests. They usually contain a font size and a letter (uppercase

Or lowercase letters ). For example,-s and-H.
2) Long Options: A long option that contains two hyphens and uppercase/lowercase letters. For example ,--

Size, -- Help, etc.
* Note: A program usually provides parameters in the form of short options and long options.

Descriptions of other types of parameters:
This type of parameter is usually followed by the options type parameter. For example, the LS-S/function shows the size of the root directory. '/

'This parameter tells ls to display the directory path.

Rules for using the getopt_long () function:

(1) Prepare two data structures before use
Character pointer type variable
The data structure includes all the short options to be defined. Each option is represented by a single letter. If this option requires parameters (for example,

File Path), followed by a colon. For example, the three short options are '-H'-o'-V', where-O requires parameters,

The other two do not need parameters. Then, we can define the data structure as follows:
Const char * const shor_options = "Ho: V ";

Struct option type array
Each element in the data structure corresponds to a long option, and each element is composed of four fields. Generally

Use Rules. The first element describes the name of the long option. The second option indicates whether the option needs to be followed by the parameter. If the parameter is required, the value is 1,

The third option can be null. The fourth option is the short option name corresponding to the long option. In addition, the last part of the data structure

An element that requires that the content of all fields be 0, that is, {null, 0, null, 0 }. The following example shows that the short option is '-H''-O'

In the '-V' example, the data structure can be defined as follows:
Const struct option long_options = {
{"Help", 0, null, 'H '},
{"Output", 1, null, 'O '},
{"Verbose", 0, null, 'V '},
{Null, 0, null, 0}
};

(2) Call Method
Refer to (1) the two data structures prepared, the call method can be:
Getopt_long (argc, argv, short_options, long_options, null );

(3) Several common return values
(A) every time you call this function, it will analyze an option and return its short options. If the analysis is complete, no options are available,

-1 is returned.
(B) If getopt_long () encounters an unspecified option during analysis, the returned value is '? ', The programmer can

To print the usage information of the defined command line to the user.
(C) when processing an option with parameters, the global variable optarg points to its parameters.
(D) When the function analyzes all the parameters, the global variable optind (into argv) points to the first 'nonoptions' position.

Example:

 

[C-sharp]
View plaincopy
  1. # Include <stdio. h>
  2. # Include <getopt. h>
  3. Char * l_opt_arg;
  4. Char * const short_options = "NBL :";
  5. Struct option long_options [] = {
  6. {"Name", 0, null, 'n '},
  7. {"Bf_name", 0, null, 'B '},
  8. {"Love", 1, null, 'L '},
  9. {0, 0, 0, 0 },
  10. };
  11. Int main (INT argc, char * argv [])
  12. {
  13. Int C;
  14. While (C = getopt_long (argc, argv, short_options, long_options, null ))! =-1)
  15. {
  16. Switch (c)
  17. {
  18. Case 'N ':
  19. Printf ("My name is XL./N ");
  20. Break;
  21. Case 'B ':
  22. Printf ("His name is St./N ");
  23. Break;
  24. Case 'l ':
  25. Rochelle opt_arg = optarg;
  26. Printf ("Our love is % s! /N ", l_opt_arg );
  27. Break;
  28. }
  29. }
  30. Return 0;
  31. }

Compile and run:

[Root @ localhost liuxltest] # gcc-O getopt. c

[Root @ localhost liuxltest] #./getopt-n-B-l forever
My name is XL.
His name is St.
Our love is forever!
[Root @ localhost liuxltest] #

[Root @ localhost liuxltest] #./getopt-Nb-l forever
My name is XL.
His name is St.
Our love is forever!
[Root @ localhost liuxltest] #./getopt-NBL forever
My name is XL.
His name is St.
Our love is forever!

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.