[Simple and clear]c C + + getopt function __ function

Source: Internet
Author: User

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 (<

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.