Programming in Linux environment (1)

Source: Internet
Author: User

Getopt (analyze command line parameters)

# Include <unistd. h>

Int getopt (INT argc, char * const argv [], const char * optstring );

Extern char * optarg;

Extern int optind, opterr, optopt;

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 is the option string, indicating which option can be processed by getopt () and which option requires parameters.

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 () is another option that does not match the optstring value during processing, an error message is displayed and the global variable optarg is set to "?" Character.

If you do not want getopt () to print the error message, set the global variable opterr to 0.

The global variables set by getopt () include:

Optarg -- pointer to the current option parameter (if any. Optind -- Re-call the index of the next argv pointer when getopt. Optopt -- the last known option.

#include<stdio.h>#include<stdlib.h>#include<unistd.h>int main(int argc,char *argv[]){int opt;while((opt = getopt(argc,argv,":if:lr")) != -1){switch(opt){case 'i':case 'l':case 'r':printf("option : %c \n",opt);break;case 'f':printf("filename : %s\n",optarg);break;case ':':printf("option needs a value\n");break;case '?':printf("Unknow option : %c\n",optopt);break;}}for(;optind < argc;optind++){printf("Argument: %s\n",argv[optind]);}exit(0);}

./Args-I-LR 'Hi there'-F Fred. C-Q

Option: I

Option: l

Option: R

Filename: Fred. c

Unknow option: Q

Argument: Hi there

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.