Command-line option resolution function (C language): Getopt () and Getopt_long ()

Source: Internet
Author: User
Tags parse error

In the morning when looking at the source project Webbench, just at the beginning was a seemingly strange function getopt_long () to get stuck, to tell the truth this function has not seen, naturally do not know what this buddy is doing. So Baidu, the original is to handle the command line options parameters, indeed, the normal point of the large program generally the first step is to handle the command line parameters, followed by the main program. In Baidu and man's help, found the specific use of methods and explanations, apart hurriedly study, and summed up the document record.

Usually in the writing process often need to handle the command line parameters, because fewer parameters, their own resolution can be done; if the number of command lines is a long time, if the order of a defined parameter meaning is easy to cause confusion, and if the program only in order to process parameters, some "optional parameters" function will be difficult to implement, This problem can be solved gracefully in Linux using functions such as getopt.

First, query the Linux command manual:
#include <unistd.h> #include <getopt.h>          /* header file */int getopt (INTARGC, char * const argv[], const char * optstring); int getopt_long (int argc, char * const argv[], const char *optstring,                          const struct option *longopts, Int*lo NGINDEX); int getopt_long_only (int argc, char * const ARGV[],CONST CHAR *optstring,                          const struct option *longopts, int* Longindex); extern char *optarg;         /* Global variables declared by the system */extern int optind, Opterr, optopt;

First take the simplest getopt function, Getopt_long is only the former enhanced version, the function of more than a point.

Second, getopt function

1. Definition :

int getopt (int argc, char * const argv[], const char *optstring);

2. Description :

Getopt is used to parse command-line option parameters, but only short options are resolved:-D 100, cannot resolve long option:--prefix

3. Parameters :

The Argc:main () function passes over the number of arguments Argv:main () function passes over the arguments of the string pointer array optstring: The option string that tells Getopt () which option to handle and which option requires parameters

4. Return :

Returns the option letter if the option is successfully found, returns 1 if all command-line options are resolved, or returns the character '? ' if the option character is not optstring. If a missing parameter is encountered, the return value depends on the first character in Optstring, if the first character is ': ' Then return ': ', otherwise return '? '. and prompts for an error message.

5, the following key examples illustrate the format meaning of optstring:

char*optstring = "AB:C::"; a single character a         means that option A has no parameter            format:-A, no parameter word multibyte colon B:     indicates that option B has and must be      in parameter format:-B 100 or-b100, but-b= 100 wrong word multibyte 2 colon C::   indicates option C can or may not     format:-c200, other format error

After this optstring is passed in, the Getopt function checks to see if the command line specifies the-a,-B and-C (which calls the getopt function multiple times until it returns-1), and the function returns the specified parameter name (that is, the letter) when it checks to see that one of the above parameters is specified.

optarg--Pointer to the current option parameter (if any). optind--the index of the next argv pointer when Getopt () is called again. optopt--last unknown option. Opterr-—— If you do not want getopt () to print error messages, simply set the global variable Opterr to 0.

The above description is not vivid, the following combination of examples to understand:

6. Example:

#include <stdio.h> #include <unistd.h> #include <getopt.h>int main (INTARGC, Char *argv[]) {    int opt;    Char *string = "A::b:c:d";    while (opt = getopt (argc, argv, string))! =-1)    {          printf ("opt =%c\t\t", opt);        printf ("Optarg =%s\t\t", optarg);        printf ("Optind =%d\t\t", optind);        printf ("argv[optind] =%s\n", Argv[optind]);    }  }

Compile the above program and execute the result:

Input options and parameters are correct

Dzlab:~/test/test#./opt-a100-b 200-c 300-dopt = a         Optarg = Optind            = 2              Argv[optind] =-bopt = b
   
    optarg =            Optind = 4              Argv[optind] =-copt = c Optarg = Optind =            6              argv[optind] =-dopt = D         optarg = (null)         Optind = 7              Argv[optind] = (NULL)
   

or this option format (note the difference):

dzlab:~/test/test#./opt-a100-b200-c300-d opt = a         Optarg =            Optind = 2              Argv[optind] =-b200opt = b         o Ptarg =            Optind = 3              Argv[optind] =-c300opt = c         optarg = Optind =            4              argv[optind] =-dopt = D
   optarg = (null)         Optind = 5              Argv[optind] = (NULL)

Option A is an optional parameter and is correct here without parameters

Dzlab:~/test/test#./opt-a-B 200-c 300-d   opt = a         Optarg = (null)         Optind = 2              Argv[optind] =-bopt = b         optarg =            optind = 4              Argv[optind] =-copt = c         optarg =            Optind = 6              Argv[optind] =-D opt = d         optarg = (null)         Optind = 7              Argv[optind] = (NULL)

Enter a case where the option parameter is wrong

Dzlab:~/test/test#./opt-a 100-b 200-c 300-dopt = a         Optarg = (null)         Optind = 2              Argv[optind] = 100opt = B
   optarg =            Optind = 5              Argv[optind] =-copt = c         optarg = Optind =            7              Argv[optind] =-dopt = D
   optarg = (null)         Optind = 8              Argv[optind] = (NULL)

Causes parse error, first optarg = null, actual input parameter 100, due to malformed format (optional parameter format fixed)

Parameter is missing, also cause error, c option is must have parameter, no parameter hint error is as follows:

Dzlab:~/test/test#./opt-a-B 200-c      opt = a         Optarg = (null)         Optind = 2              Argv[optind] =-bopt = b         Optarg =            Optind = 4              Argv[optind] =-c./opt:optionrequires an argument--' c ' opt =?         Optarg = (null)         Optind = 5              Argv[optind] = (NULL)

In this case, the first letter in the optstring is not ': ', if the first letter in the optstring is added ': ', then the option for the last missing parameter is ': ', not '? ', and there is no error message, no longer listed here.

The command-line option is undefined, and the-e option is not defined in optstring and will cause an error:

Dzlab:~/test/test#./opt-a-B 200-eopt = a         Optarg = (null)         Optind = 2              Argv[optind] =-bopt = b         Optarg = 2 XX             optind = 4              Argv[optind] =-e./opt:invalidoption--' e ' opt =?         Optarg = (null)         Optind = 5              Argv[optind] = (NULL)

Here should have explained the function of the getopt function clearly, the bottom of the Getopt_long function, the Getopt_long function contains the function of the getopt function, and can also specify "long parameters" (or long options), and getopt function comparison, Getopt_long has two more parameters than it:

three, Getopt_long function

1. Definition :

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

2. Description :

Includes getopt function, added the ability to resolve long options such as:--prefix--help

3. Parameters :

Longopts    indicates the name and property of the long parameter Longindex   if Longindex is not NULL, the variable it points to will record the current found parameter in accordance with the description of the first element in Longopts, that is, the subscript value of longopts

4. Return :

For the short option, the return value is the same as the getopt function; for the long option, if flag is null, return Val, otherwise return 0; return value for error condition same as getopt function
5. struct option
struct option {const char  *name;       /* Parameter name */int          has_arg;    /* Indicates whether the parameter */int          *flag;      /* Flag=null, returns value when NOT NULL, *flag=val, returns 0 */int          val;        /* is used to specify the value of the function to find the return value of the option or flag non-null when specifying *flag */};

6. Parameter Description:

Has_arg  Indicates whether a parameter value is used, and its value is optional: No_argument indicates that the         long option does not take parameters, such as:--name,--helprequired_argument  indicates that the long option must have parameters, such as:--prefix/root or--prefix=/rootoptional_argument  indicates that the parameters of the long option are optional, such as:--help or –prefix=/root, others are errors

Then take a look at the example operations to understand more profoundly:

7. Example:

int main (INTARGC, Char *argv[]) {    int opt;    int digit_optind = 0;    int option_index = 0;    Char *string = "A::b:c:d";    static struct option long_options[] =    {          {"Reqarg", Required_argument,null, ' R '},        {"Optarg", Optional_ Argument,null, ' O '},        {"Noarg",  no_argument,         null, ' n '},        {null,     0,                      null, 0},    };     while (opt =getopt_long_only (argc,argv,string,long_options,&option_index))! =-1)    {          printf ("opt =%c\ T\t ", opt);        printf ("Optarg =%s\t\t", optarg);        printf ("Optind =%d\t\t", optind);        printf ("Argv[optind] =%s\t\t", Argv[optind]);        printf ("Option_index =%d\n", option_index);    }  }

Compile the above program and execute the result:

Case where the long option is entered correctly

Dzlab:~/test/test#./long--reqarg--optarg=200--noargopt = r optarg =100     optind = 3   Argv[optind] =--optarg=2 xx  option_index = 0opt = o Optarg =200     optind = 4   Argv[optind] =--noarg        option_index = 1opt = N Optarg = ( NULL) Optind = 5    Argv[optind] = (null)          Option_index = 2

Or this way:

dzlab:~/test/test#./long–reqarg=100--optarg=200--noargopt = r optarg =100     optind = 2   argv[optind] =--optarg=  Option_index = 0opt = o Optarg =200     optind = 3   Argv[optind] =--noarg        option_index = 1opt = n Opta RG = (NULL) Optind = 4    Argv[optind] = (null)          Option_index = 2

Optional option can not give parameters

Dzlab:~/test/test#./long--reqarg--optarg--noarg   opt = r Optarg =100     optind = 3     Argv[optind] =--optarg Option_index = 0opt = o Optarg = (null) Optind = 4      argv[optind] =--noarg   option_index = 1opt = n Optarg = (null) opt IND = 5      Argv[optind] = (null)     Option_index = 2

Enter the case of a long option error

Dzlab:~/test/test#./long--reqarg--optarg--noarg opt = r Optarg =100     optind = 3     Argv[optind] =--optarg< c10/>option_index= 0opt = o Optarg = (null) Optind = 4      argv[optind] =200        option_index = 1opt = n Optarg = (null) o Ptind = 6      Argv[optind] = (null)     Option_index = 2

At this point, although there is no error, but the second item in the OPTARG parameter is not parsed correctly (the format should be-optarg=200)

You must specify an option for the parameter, and if you do not give the parameter, the same parse error is:

Dzlab:~/test/test#./long--reqarg--optarg=200--noarg    opt = r Optarg =--optarg=200  optind = 3 Argv[optind] =--no arg  option_index = 0opt = n Optarg = (null)         Optind = 4 Argv[optind] = (null)    Option_index = 2

Examples of long options for the time being so many, other things such as wrong options, missing parameters, the format is not correct to try again.

Four, getopt_long_only function

The Getopt_long_only function uses the same parameter table as the Getopt_long function, basically consistent in function, except that Getopt_long only treats--name as a long parameter, but Getopt_long_only will--name and-name two Options are matched as long parameters. getopt_long_only If the option-name cannot be matched in longopts, but can match a short option, it resolves to a short option.

Command-line option resolution function (C language): Getopt () and Getopt_long ()

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.