Use getopt to parse command line parameters

Source: Internet
Author: User
A very important step in the programming of using getopt to parse command line parameters (c) CLI (command line interface) is the parsing of command line parameters. For the first brothers involved in this section, argv and argc are still very tedious. This article briefly introduces the usage of several command line parameter parsing functions related to getopt, and introduces several simple examples to help readers master its usage. The following APIs are intercepted and simplified from Man 3 getopt. This function is initially defined in unistd. h. Only short parameter formats like-a-d are supported, and long parameter formats like -- color -- dir are not supported. Int getopt (INT argc, char * const argv [],
Const char * optstring); this function is defined in getopt. H, and implements mixed parsing of long and short parameters. Int getopt_long (INT argc, char * const argv [],
Const char * optstring,
Const struct option * longopts, int * longindex); this function is defined in getopt. h and only supports long Parameter Parsing. Int getopt_long_only (INT argc, char * const argv [],
Const char * optstring,
Const struct option * longopts, int * longindex); in practical use, of course, a function in the middle is the most used, and no one wants to use its own CLI Program What about short parameters and long parameters? Short Parameter definition: getopt uses the string referred to by optstring as the short parameter list, as "1ac: D:" is a short parameter list. A short parameter is defined as a '-' followed by a letter or number, such as-a, and-B is a short parameter. Each number or letter defines a parameter. The short parameters are divided into three types in the getopt definition: 1. A parameter without a value is defined as the parameter itself. A parameter with a value is defined by adding a colon 3 after the parameter itself. optional value parameter, which is defined by adding two colons after the parameter itself. Here, we take the "1ac: D:" as an example to describe, where 1, A is a parameter without a value, C is a parameter with a value, and D is a parameter with an optional value. In actual calls, '-1-a-c cvalue-d','-1-a-c cvalue-ddvalue ', '-1A-ddvalue-C cvalue' is valid. Note the following three points: 1. parameters without values can be written in a row. For example, parameters with values 1 and A can be written separately through-1-A or-1A or-A1. 2. parameters are in different order. The resolution results of '-1A-C cvalue-ddvalue' and '-D-C cvalue-a1' are the same. note that there must be no space between the values of the optional values and the parameters. The values must be written in the format of-ddvalue. If the values are written in the format of-D dvalue, an error will be parsed. The return value of getopt (): getopt () returns the value of-1 for the argument passed in from the command line each time it is called. If a parameter not included in optstring is parsed, or a required parameter without a value '? 'When optstring starts with ':', ':' instead of '? Is returned if a value is missing '? 'Getopt () error message: When getopt is used, some error messages that we do not want will often appear when the parameter is incorrect. This is the error message output by getopt through stderr. We can solve this problem by setting opterr to 0. Obtain the parameter value: When the parameter is followed by a value, the value will be placed in the optarg string after the call; if there is no value, the string will be left blank. Three parsing modes of getopt (): 1. By default, getopt () will parse parameters according to the sequence defined by optstring. If the parameter is not defined by optstring, it will return ?, Put the non-parameter value at the end of the argv queue. 2. When optstring is defined with '+', getopt () skips all parameters not in optstring and sends them as non-parameter values to the end of the queue. 3. When optstring is defined starting with '-', it is not understood .... Example 1: Use getopt () to parse short parameters. # Include <stdio. h>
# Include <unistd. h> void parse_arg (INT argc, char * argv [])
{Int C;
Opterr = 0; while (1)
{
C = getopt_long (argc, argv, ": 1ac: D:"); If (C =-1)
{
Break;
} Switch (c)
{
Case '1 ':
Case 'A ':
Printf ("option % C \ n", C );
Break; Case 'C ':
Printf ("option C with value '% s' \ n", optarg );
Break; Case 'D ':
If (optarg! = NULL)
{
Printf ("option D with value '% s' \ n", optarg );
}
Else
{
Printf ("option D \ n ");
}
Break; case '? ':
Printf ("unknown parameter: % C \ n", optopt );
Break; Case ':':
Printf ("need parameter: % C \ n", optopt );
Break; default:
Printf ("?? Getopt returned character code 0% o ?? \ N ", C );
Break ;}} if (optind <argc)
{
Printf ("non-option argv-elements :");
While (optind <argc)
{
Printf ("% s", argv [optind ++]);
}
Printf ("\ n ");
} Int main (INT argc, char * argv [])
{
Parse_arg (argc, argv );
Return 0;
} Example 2: Use getopt_long () to implement hybrid parsing of long and short parameters. Disadvantage: getopt does not provide the mandatory parameter or optional parameter list function. It only proposes a method for obtaining parameters. In actual use, after using getopt to parse the parameter, it is still cumbersome to verify the existence or validity of the parameter of the program. We hope to solve this problem well in future applications. Finally, getopt only parses command line parameters in an established mode. Since it is an established model, it must have its shortcomings. If you encounter some issues that cannot be solved by getopt in actual use, you must write your own method to parse the command line parameters. Maybe one day there will be a command line parsing library that is more perfect than getopt

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.