Getopt_long function Parsing command-line arguments

Source: Internet
Author: User


Every day you are using a lot of command-line programs, is not it feel that the command line parameters used more convenient, they are using getopt to achieve.

Using getopt to write programs under Linux is a cool thing, here is a brief introduction to the use of getopt.

= = = Getopt Use = = =

Before we discuss parameter processing, we first identify two concepts: options, option parameters
GCC-G-O test test.c
We often use the above command to compile the program, where G and O is the option, where test is the o option parameter

Here's a look at getopt:

The first is the function declaration:

1#include <unistd.h>2 extern Char*Optarg;3 extern intOptind;4 extern intoptopt;5 extern intOpterr;6 extern intOptreset;7 intGetoptintargcChar*Const*ARGV,Const Char*optstring);

Look directly at an example:

1 /*getopt.c*/2#include <unistd.h>3#include <stdio.h>4 intMainintargcChar*argv[])5 {6     intaflag=0, bflag=0, cflag=0;7     intch;8      while(ch = getopt (argc, argv,"Ab:c")) != -1)9     {Tenprintf"Optind:%d\n", optind); One         Switch(CH) { A          Case 'a': -printf"Have option:-a\n"); -Aflag =1; the              Break; -          Case 'b': -printf"Have option:-b\n"); -Bflag =1; +printf"The argument of-b is%s\n", optarg); -              Break; +          Case 'C': Aprintf"Have option:-C"); atCflag =1; -              Break; -          Case '?': -printf"Unknown option:%c\n",(Char) optopt); -              Break; -         } in     } -}

From the above example, you should be able to tiger, you can use the Getopt function in your own program.

Getopt () Returns an option once per call.
ARGC and argv are obviously the two parameters of the main function.
The string optstring can contain the following elements: a single character followed by a colon followed by an option parameter, followed by a two colon followed by a parameter that follows an optional option. For example, an option character "X" represents the option "-X", the option character "×:" represents the option and its parameter "-x argument", the option character "×::" means that the parameter of option X is optional ("::" is the GNU addition, not necessarily available under all UNIX systems).
After the return of Getopt (), if there is an option argument optarg points to the option parameter, and the variable Optind contains the next argv parameter as an index to the next call to Getopt (). The variable optopt holds the last known option returned by Getopt ().
When the parameter column has reached the end of the getopt () function returns-1, Getopt returns '? ' When an unknown option is encountered. The interpretation of the option in the parameter sequence may be canceled because it causes getopt () to send an end signal to the parameter processing and return-1.

Many times, we do not want to output any error messages, or we prefer to output our own defined error messages. You can change the error message output behavior of the getopt () function in the following two ways:
Before calling Getopt (), set Opterr to 0 so that you can force it to output no messages when the getopt () function finds an error.
If the first character of the optstring parameter is a colon, then the getopt () function remains silent and returns different characters depending on the error condition, as follows:
"Invalid option" ――getopt () returns '? ', and Optopt contains invalid option characters (this is normal behavior).
"Missing option parameter" ――getopt () returns ': ' If the first character of optstring is not a colon, then getopt () returns '? ', which makes this case not separate from the case of invalid options.
For example, optstring is: a:b::c, which means a with a parameter, b optional, C without parameters
If you enter D, "invalid option", Getopt returns '? '
If the input a forgets to take parameters, "missing option parameter", getopt should return ': '; if the first character that is no longer optstring is not ': ' Then the error will be treated as an "invalid parameter", thus getopt return '? ' , which makes it impossible to distinguish between error types

Like what:
[Email protected]:~/desktop/advanced Linux programming/alp-listings/trainning$./getopt-a-d-b foo
Have option:-A
./getopt:invalid Option--D
Unknown option:d
Have option:-B
The argument of-b is foo
[Email protected]:~/desktop/advanced Linux programming/alp-listings/trainning$./getopt-a---c-b foo
Have option:-A

Getopt source code is below, Getopt will only explain to-a.

The variables Opterr and optind are initialized to 1. If you want to take the first few arguments of the command line, you can set Optind to a different value before calling Getopt ().
If you do not want the getopt () output error message, set the global variable Opterr to 0.

It is not easy to use Ah!

= = = Getopt_long Use = = =

I dare say, almost everyone in contact with a new command, the first thing to do is cmd-h or cmd--help,-h we all know is to use getopt to achieve, then--help how to achieve it? That's getopt_long, he can support long parameters.

First look at an example program:

1#include <stdio.h>2#include <getopt.h>3 4 intDo_name, Do_gf_name;5 Char*L_opt_arg;6 7 Static Const Char*shortopts ="L:ng";8 structOption longopts[] = {9{"name", No_argument, NULL,'N'},Ten{"Gf_name", No_argument, NULL,'g'}, One{" Love", Required_argument, NULL,'L'}, A{0,0,0,0}, - }; -  the intMain (intargcChar*argv[]) - { - intC; -  +  while((c = Getopt_long (argc, argv, shortopts, longopts, NULL))! =-1) -     { +       Switch(c) A    { at     Case 'N': -printf ("My name is lyr.\n"); -        Break; -     Case 'g': -printf ("Her name is bx.\n"); -        Break; in     Case 'L': -L_opt_arg =Optarg; toprintf ("Our love is %s!\n", l_opt_arg); +        Break; -    } the     } * return 0; $}

In the code we use Getopt_long to parse the long options, where we use an array of struct-struct options, struct options longopt[].
The struct options are defined as follows:

1 struct option{2      Const Char *name; 3      int Has_arg; 4      int *flag; 5      int Val; 6 };

The elements in the structure are explained as follows:
const CHAR *name
This is the option name and there is no dash in front. such as "Help", "verbose" and so on.

int Has_arg
Describes whether the option has option parameters. If there is, what type of parameter, at this point, its value must be one of the following table.
Symbolic constant numeric meaning
No_argument 0 Option No parameters
Required_argument 1 options require parameters
Optional_argument 2 option parameter optional

int *flag
If this pointer is null, then Getopt_long () returns the value in the Val field of the structure. If the pointer is not Null,getopt_long (), the variable it points to is populated with the value in the Val field, and Getopt_long () returns 0. If flag is not NULL, but no long option is found, then the value of the variable it points to does not change.

int Val
This value is the value returned when the long option is found, or flag is not NULL when loaded into the *flag. Typically, if flag is not NULL, Val is a true/False value, such as 1 or 0; On the other hand, if flag is null, then Val is usually a character constant, and if the long option is the same as the short option, then the character constant should be the same as the parameter for this option that appears in Optstring.

Each long option has a separate entry in the Long Options table, which needs to fill in the correct values. The value of the last element in the array should be all 0. The array does not need to be sorted, and Getopt_long () does a linear search. But sorting by long names makes it easier for programmers to read them.

Let's look at this structure in the program:

1 structOption longopts[] = {2{"name", No_argument, NULL,'N'},3{"Gf_name", No_argument, NULL,'g'},4{" Love", Required_argument, NULL,'L'},5{0,0,0,0},6};

The structure illustrates three common options, name, Gf_name, and love three options, where love requires options, and their respective short options are N, G, L.
Note: The third parameter flag for the struct in the structure array above is null.

Program Run Result:
[Email protected]:~/desktop/advanced Linux programming/alp-listings/trainning$./getopt_long--name
My name is LYR.
[Email protected]:~/desktop/advanced Linux programming/alp-listings/trainning$./getopt_long-n
My name is LYR.
[Email protected]:~/desktop/advanced Linux programming/alp-listings/trainning$./getopt_long-l Me
Our Love is me!
[Email protected]:~/desktop/advanced Linux programming/alp-listings/trainning$./getopt_long--love Me
Our Love is me!
[Email protected]:~/desktop/advanced Linux programming/alp-listings/trainning$

= = = Reference = =
Features of the getopt () function provided by GNU
Using getopt () for command line processing

= = = Questions = =
1. How to specify optional parameters in Getopt
2, can be implemented using an option with multiple parameters, such as Scanner-i

Getopt_long function Parsing command-line arguments

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