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