Getopt usage in Linux

Source: Internet
Author: User

Http://apps.hi.baidu.com/share/detail/17204074

Getopt is used to parse command line option parameters. You don't have to write your own stuff to process argv.

# Include <unistd. h>
Extern char * optarg; // parameter pointer of the option
Extern int optind, // when getopt is called next time, check the option again from the position where optind is stored.
Extern int opterr, // when opterr = 0, getopt does not output an error message to stderr.
Extern int optopt; // when the command line option character is not included in optstring or the option lacks necessary parameters, this option is stored in optopt, and getopt returns '? ',
Int getopt (INT argc, char * const argv [], const char * optstring );
Call once and return an option. If the option parameter in the command line does not check any more options contained in optstring,-1 is returned, and optind stores the first command line parameter that does not contain the option.

First, let's talk about what is an option and what is a parameter.

The optstring can contain the following elements,
1. A single character, indicating options,
2. A single character followed by a colon: indicates that this option must be followed by a parameter. Parameters are immediately followed by options or separated by spaces. The pointer of this parameter is assigned to optarg.
3. A single character is followed by two colons, indicating that this option must be followed by a parameter. Parameters must be followed by no space. The pointer of this parameter is assigned to optarg. (This feature is the expansion of GNU ).

Getopt processes command line parameters starting with '-', such as optstring = "AB: C: D:". The command syntax getopt.exe-a-B Host-ckeke-D haha
In this command line parameter,-A and-H are the option elements. Removing '-', A, B, and C is the option. Host is the parameter of B, and Keke is the parameter of C. However, haha is not a parameter of D because they are separated by spaces.

Note that by default, getopt will rearrange the order of command line parameters, so all command line parameters that do not contain the options are ranked at the end.
For example, getopt.exe-A ima-B Host-ckeke-D Haha, the order of the last command line parameters is-a-B Host-ckeke-D IMA haha.
If the character string in optstring starts with '+' or the environment variable posixly_corre is set. If you encounter a command line parameter that does not contain the option, getopt will stop and-1 will be returned.

# Include <stdio. h>
# Include <stdlib. h>
# Include <unistd. h>

Int main (INT argc, char ** argv)
{
Int result;

Opterr = 0; // make getopt unavailable stderr output error message

While (result = getopt (argc, argv, "AB: C ::"))! =-1)
{
Switch (result)
{
Case 'A ':
Printf ("option = A, optopt = % C, optarg = % s \ n", optopt, optarg );
Break;
Case 'B ':
Printf ("option = B, optopt = % C, optarg = % s \ n", optopt, optarg );
Break;
Case 'C ':
Printf ("option = C, optopt = % C, optarg = % s \ n", optopt, optarg );
Break;
Case '? ':
Printf ("result = ?, Optopt = % C, optarg = % s \ n ", optopt, optarg );
Break;
Default:
Printf ("default, result = % C \ n", result );
Break;
}
Printf ("argv [% d] = % s \ n", optind, argv [optind]);
}
Printf ("result =-1, optind = % d \ n", optind); // check the position of the last optind.

For (result = optind; Result <argc; Result ++)
Printf ("----- argv [% d] = % s \ n", result, argv [Result]);

// Check the final command line parameters to see if the order has changed.
For (result = 1; Result & lt; argc; Result ++)
Printf ("\ Nat the end ----- argv [% d] = % s \ n", result, argv [Result]);
Return 0;
}
Unistd has an optind variable. After each getopt operation, this index points to the next index of the string currently analyzed in argv. Therefore
Argv [optind] can get the next string. You can determine whether it starts. Below is a test program
# Include & lt; stdio. h>
# Include <unistd. h>
Int main (INT argc, char * argv [])
{
Int TMP = 4;
While (TMP = getopt (argc, argv, "abck "))! =-1)
{
Printf ("-% C \ t", TMP );
Int opt = optind;
While (OPT <argc)
{
If (argv [opt] [0]! = '-')
{
Printf ("% s \ t", argv [opt]);
Opt ++;
}
Else
Break;
}
Printf ("\ n ");
}
Getchar ();
} & Lt; IFRAME Style = "position: absolute; top: 0px; left: 0px" id = "google_ads_frame1" Height = "90" marginheight = "0" src = "http://googleads.g.doubleclick.net/pagead/ads? Export & dt = 1282807644948 & SHV = r20100812 & correlator = 1282807644948 & FRM = 0 & adk = 3547809575 & ga_vid = 2053430233.1261390632 & ga_sid = 1282807645 & ga_hid = 545826158 & ga_fc = 1 & u_tz = 480 & u_his = 0 & u_java = 1 & u_h = 751 & u_w = 1202 & u_ah = 726 & u_aw = 1202 & u_cd = 32 & u_nplug = 0 & u_nmime = 0 & biw = 1185 & BiH = 585 & ref = http % 3A % 2f % 2fwww.google.com.hk % 2 fsearch % 3fhl % 3dzh-cn % 26 newwindow % 3d1% 26 safe % 3 dstrict % 26q % 3 dgetopt % 26aq % 3df % 26aqi % 3d % 26aql % 3d % 26oq % 3d % 26gs_rfai % 3d & Fu = 0 & IFI = 1 & DTD = 62 & xpc = iqm1uspbj4 & P = http % 3A // www.cnitblog.com "frameborder =" 0 "; 728 "allowtransparency =" allowtransparency "name =" google_ads_frame "marginwidth =" 0 "scrolling =" no ">

Function Description getopt () is used to analyze command line parameters. The argc and argv parameters are the number and content of parameters passed by main. The optstring parameter indicates the option string to be processed. This function returns the option letter in argv, which corresponds to the letter in the optstring parameter. If the letter in the option string is followed by the colon ":", it indicates that there are related parameters. The global variable optarg points to this additional parameter. If getopt () fails to find the correct parameter, an error message is printed and the global variable optopt is set to "?". If you do not want getopt () to print the error message, set the global variable opterr to 0.
Return Value: If a matching parameter is found, a letter is returned. If the parameter is not included in the option Letter of The optstring parameter, "?" is returned. Character.-1 is returned when the analysis ends.
Example # include <stdio. h>
# Include <unistd. h>
Int main (INT argc, char ** argv)
{
Int ch;
Opterr = 0;
While (CH = getopt (argc, argv, "a: bcde "))! =-1)
Switch (CH)
{
Case 'A ':
Printf ("Option A: '% s' \ n", optarg );
Break;
Case 'B ':
Printf ("Option B: B \ n ");
Break;
Default:
Printf ("other option: % C \ n", CH );
}
Printf ("optopt + % C \ n", optopt );
}
Run $./getopt-B
Option B: B
$./Getopt-C
Other option: c
$./Getopt-
Other option
$./Getopt-a12345
Option A: '20140901'

Getopt Function

Function Definition:
# Include
Int getopt (INT argc, char * const argv [],
Const char * optstring );

Extern char * optarg;
Extern int optind, opterr, optopt;

# DEFINE _ gnu_source
# Include

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 );

The getopt () function is used to parse command line parameters. Here, we mainly explain getopt_long ().

The first two parameters of getopt_long (), argc and argv are the number of parameters passed to main () and the parameter array (and the argc and argv of main () are a concept ).

In getopt_long (), optstring is a string that indicates acceptable parameters. For example, "A: B: cd" indicates that the acceptable parameters are A, B, C, and D.

With more parameter values. (For example,-a host -- B name)

In getopt_long (), the longopts parameter is actually a structured instance:
Struct option {
Const char * Name;
// Name indicates the long parameter name
Int has_arg;
// Has_arg has three values, no_argument (or 0), indicating that this parameter is not followed by the parameter value
// Required_argument (OR 1), indicating that this parameter must be followed by a parameter value
// Optional_argument (or 2), indicating that the parameter can be followed or not with the parameter value
Int * flag;
// Determines the return value of getopt_long. If the flag is null, the function returns the Val value that matches the option.
Int val;
// The return value is determined jointly with the flag.
}

Here is an example:

Struct option long_options [] = {
{"A123", required_argument, 0, 'A '},
{"C123", no_argument, 0, 'C '},
}

Now, if the command line parameter is-a 123, calling getopt_long () will return the character 'a', and the string 123 will be returned by optarg (note! String 123 with optarg

Back! Optarg does not need to be defined. It is already defined in getopt. H)
If the command line parameter is-C, calling getopt_long () will return the 'C' character. At this time, optarg is null.

Finally, when getopt_long () resolves all parameters in the command line, return-1.

It seems that I am a little confused. So, let's look at an example. I believe that the code can best illustrate the problem:

# Include
# Include
# Include
# Include

Int main (INT argc, char ** argv)
{

Struct option long_options [] = {
{"A123", required_argument, 0, 'A '},
{"C123", no_argument, 0, 'C '},
}
Int OPT;
Printf ("starting ...");
While (OPT = getopt_long (argc, argv, "A: C", long_options, null ))! =-1)
{
Switch (OPT)
{
Case 'A ':
Printf ("It's! ");
Printf ("string of A: % s", optarg );
Break;
Case 'C ':
Printf ("It's C! ");
Break;
Default:
Printf ("You shoshould look for help! ");
Exit (1 );
Break;
}
}
Printf ("end ...");
Return 0;
}

After compilation, let's test if a. Out is generated.
./A. Out-a hello-C
Output:
Starting...
It's!
String Of A: Hello
It's C!
End...

Link: http://www.cnitblog.com/zouzheng/archive/2007/04/02/25034.html

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.