Turn from: http://speakingbaicai.blog.51cto.com/5667326/1074671
/*
Prototype: int getopt (int argc, char * const argv[], const char *optstring);
Four Global variables:
extern char *optarg; A pointer to the parameter of the option.
extern int Optind,//storage location, the next time you call getopt, restart the check option from the location where Optind is stored.
extern int Opterr,//When opterr=0, getopt does not output error information to stderr.
extern int optopt; This option is stored in optopt when the command-line option characters are not included in optstring or if the option lacks the necessary parameters.
About optstring:
such as: Optstring=ab:c::d:: When,
1, Ab:c::d:: means that there are four options-a-b-c-d;
2, where the B c d option followed by a colon to indicate B C D must follow the parameters;
3, b After a colon, the entries and options can be a space between, but also did not;
4, C D is followed by a two colon, indicating that the parameters after C D must be immediately following the option.
such as:./a.out-a-B ARGOFB-CARGOFC-DARGOFD
If written as:./a.out-a-B argofb-c argofc-dargofd the parameter after the C option is actually null
The main points of attention when using getopt:
1, getopt each call once, return an option, note that the option is not a parameter;
2, Optarg store the getopt returned options after the parameters, the option is null after the parameter (the actual runtime does not or optstring in the option after not: are considered null);
3, when no longer check the optstring contains the option to return-1;
4. When checking the option that is not in optstring or missing the necessary parameters, return. And the option exists in optopt.
Summarize:
When used, simply denoted getopt return option, Optarg point to parameters.
*/
#include <unistd.h>
int main (int argc, char **argv)
{
int opt;
Opterr = 0;
while (opt = getopt (argc, argv, "AB:C::d::")!=-1)
{
Switch (OPT)
{
Case ' a ':
printf (<