C Language command-line parsing functions: Getopt/getopt_long

Source: Internet
Author: User

The parameter options under the command-line tool are available in two, long and short options . The short option starts with--a single letter followed by a long option--to start with, followed by multiple letters.


I. getopt ()

1. Function : Parse command line short option parameter

2. Function Prototypes:

#include <getopt.h>int. getopt (intcharconstConstChar *optstring);

Several external variables declared in the getopt.h:
extern char *optarg;
extern int Optind, opterr, optopt;

Optarg: If there is a parameter after the short option, Optarg points to the parameter
Optind: Identifies the index of the next option when the scan option is complete, identifying the first non-option parameter index after the scan is completed
Opterr: When an unrecognized option occurs, getopt prints an error message. Set Opterr to 0 to print error messages.
Optopt: Store An unrecognized option to optopt

3. Parameters
ARGC: Number of parameters (main)
argv: Parameter array (main)
Optstring: Short-choice character set, such as I,n in-i-n
If the option is followed by a parameter, the option character is appended: the corresponding parameter value is saved in the external variable Optarg
If optstring is "i:a", then the program supports two short options-I arg and-a, and I must have parameter values after
When the./a.out-i filename-a is executed, the Optarg pointer points to the filename

4. Parsing process
Getopt first scans argv[1] to argv[argc-1], and then places the options and parameters on the leftmost side of the argv array, and the non-option arguments are placed in turn to the last side of the argv
That is, the function changes the order in which the argv are arranged.

If the execution procedure is:

     0         1    2    3    4  5    6     7  8   9  $ . /mygetopt file1-i infile-a-o outfile-v-H file2

During the scan, Optind is the index of the next option (such as-I,-A,-O,-V), the non-option parameter is skipped, and the optind is increased by 1. The Optind initial value is 1.
When scanning argv[1], for non-option parameters, skip, optind=2; When you scan to the-I option, the following parameters are followed, and the next option to scan is-A, optind is changed to 4;
When scanning to the-a option, the next option is-o,optind=5; When scanning to the-o option, parameters are followed, and the next option is-v,optind=7; When you scan to the-v option, the next
option is-h,optind=8; Scan to-h option is finished, optind=9

After the scan is complete, getopt modifies the argv array to the following form (optstring is specified as "I:AO:VH"):

     0       1    2    3  4    5     6  7   8     9 $. /mygetopt-i infile-a-o outfile-v-H file1 file2

At the same time,Optind will point to the first parameter of the non-option , as above, Optind will point to File1

5. Return value

If Getopt finds a short option character, the option character is returned, in this case I a O v H.
If an unacceptable option character or missing option parameter is present, the optopt will be set to the corresponding option character;
Then no option character is followed, 1 is returned

6. Test procedures

#include <stdio.h>#include<getopt.h>voidUsageConst Char*p) {printf ("Usage:%s [-I infile] [-A] [-o outfile] [-v] [-h] [file]\n", p);}intMainintargcChar*argv[]) {    intCh=0; Opterr=0;//prevent error information to print for unrecognized options     while(Ch=getopt (argc, argv,"I:AO:VH") ) != -1 )    {        Switch(CH) { Case 'I': printf ("option I:%s\n", Optarg);/*optind: parameter is index of option parameter (starting from 1)*/printf ("optind=%d\n\n", Optind);  Break;  Case 'a': printf ("option A:%c\n", CH); printf ("optind=%d\n\n", Optind);/*optind: No parameter is an index of the option itself (starting from 1)*/             Break;  Case 'o': printf ("option o:%s\n", Optarg); printf ("optind=%d\n\n", Optind);  Break;  Case 'v': printf ("option V:%c\n", CH); printf ("optind=%d\n\n", Optind);  Break;  Case 'h': Usage (argv[0]); printf ("optind=%d\n\n", Optind);  Break; default: printf ("Unrecognized option:%c\n", optopt); Usage (argv[0]); }} printf ("Optind =%d\n", Optind); if(Optind <argc) {printf ("\nnon-option Arguments below:\n");  while(Optind <argc) {printf ("%s\n", argv[optind++]); }    }     for(ch=0; ch<argc; ch++) {printf ("%s", Argv[ch]); } printf ("\ n"); return 0;}
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
[Email protected]:~/mytest/test$/pp file1 file2-i infile-a Baidu sina-o outfile-v renmin Google-h Bluestar file2option i:infileoptind=5option A:aoptind=6option O:outfileoptind=Tenoption V:voptind= OneUsage:./pp [-I infile] [-A] [-o outfile] [-v] [-h] [File]optind=/*-h because it has no parameters, it is the next element directly * /Optind=8/* First illegal parameter * /Non-option arguments below:file1 file2 Baidu Sina renmin Google Bluestar file2

0 1 2 3 4 5 6 7 8 9/pp-i infile-a-o outfile-v-h file1 file2 Baidu Sina renmin Google Bluestar file2

Note:
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 ().
Before calling Getopt (), set Opterr to 0 so that you can force it to output no messages when the getopt () function finds an error.

Second, Getopt_long ()

1. function
Command line parsing with support for long options

2. Prototypes
int Getopt_long (int argc, char * const ARGV[],CONST char *optstring, const struct option *longopts,int *longindex);

3. Parameters
ARGC and argv are usually passed directly from the two parameters of main ()
Optsting is a string of option parameters that represents an acceptable parameter. For example, "A:B:CD"
Longopts is a struct array, and the option structure is called the long option table, which is declared as follows:
struct Option {
const char *name;
int has_arg;
int *flag;
int Val;
};

The elements in the structure are explained as follows:
const char *name: Option name, not preceded by a dash. such as "Help", "verbose" and so on.
int Has_arg: Describes whether the long option has an option parameter, and if so, what type of parameter is the value shown in the following table:
Symbolic constant numeric meaning
No_argument 0 Option No parameters
Required_argument 1 options require parameters
Optional_argument 2 option parameter is optional
NT *flag: If the pointer is null, then Getopt_long returns the value of the Val field, and if the pointer is not NULL, it will point to
The structure fills in the value of the Val field, and Getopt_long returns 0;
int val: If flag is null, then Val is usually a character constant, and if the short option and the long option are the same, then the character should appear in the optstring
The parameters of this option are the same;

The Longindex parameter is generally assigned null, and if it is not set to NULL, it points to a variable that is assigned the long option found in longopts
The index value in, which can be used for error diagnosis.

There are two ways to do the options type parameter:
1) Short options: They usually contain a hyphen and a letter (uppercase or lowercase letters). For example:-s,-h and so on.
2) long options: contains two hyphens and a few uppercase and lowercase letters. For example,--size,--help and so on.

4. Return value
Each time Getopt_long is called, it parses a symbol, returns the corresponding short option character, and returns 1 if parsing is complete.
If Getopt_long encounters an invalid option character, it prints an error message and returns '? '
When Getopt_long resolves to a long option and discovers that no arguments are followed, return ': ', indicating a lack of parameters.

When a parameter is processed, the global variable Optarg points to the next variable to be processed. When Getopt_long finishes processing all the options, the global change
The amount Optind points to the first unknown option index.

#include <stdio.h>#include<getopt.h>intDo_name, Do_gf_name;Char*L_opt_arg;Static Const Char*shortopts ="L:ng";structOption longopts[] = {  {"name", No_argument, NULL,'N'},  {"Good", No_argument, NULL,'g'},  {" Love", Required_argument, NULL,'L'},  {0,0,0,0},};intMain (intargcChar*argv[]) {    intC;  while((c = Getopt_long (argc, argv, shortopts, longopts, NULL))! =-1)    {        Switch(c) { Case 'N': printf ("nnnnn.\n");  Break;  Case 'g': printf ("ggggg.\n");  Break;  Case 'L': L_opt_arg=Optarg; printf ("%s!\n", L_opt_arg);  Break; }    }    return 0;}

6. Results

$./DD--namennnnn.$. /DD--goodggggg.$. /DD--Loveyouyou!

C Language command-line parsing functions: Getopt/getopt_long

Related Article

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.