Before we discuss this function, we first understand two concepts: options and their parameters
Gcc-o program PROGRAM.C
In the above command,-O is the option program is the parameter.
Getopt ();
Header file:
#include <unistd.h>
Function Prototypes:
int getopt (int argc,char * CONST argv[],const char * optstring);
ARGC is the number of arguments, and argv is an array of pointers.
External variables
extern char *optarg; The parameter pointer of the option, pointing to the next parameter to be scanned
extern int Optind,//index as subscript for next pointer to be processed
extern int Opterr,//When opterr=0, getopt does not output error messages to stderr, instead of 0, an error message is printed to Sterr
extern int optopt; Used to store incorrect or unknowable information, which is stored in optopt,getopt returns a question mark (?) when the command-line option character is not included in optstring or if the option lacks the necessary parameters.
Optstring the specifications of the parameters
1. Single character, indicating options,
2. A single character followed by a colon (:) indicates that the option must follow a parameter. Parameters are immediately followed by options or separated by a space. The pointer to the parameter is assigned to Optarg.
3 A single character followed by a two colon (::), which indicates that the parameter after the option is optional. If so, the parameters must be immediately followed by an option and cannot be separated by a space. The pointer to the parameter is assigned to Optarg.
e.g.
/*getopt.c*/
1#include <stdio.h>2#include <stdlib.h>3#include <unistd.h>4 intMainintargcChar*argv[])5 {6 intopt;7 while(Opt=getopt (ARGC,ARGV,"ab:c::"))!=-1){8 Switch(opt) {9 Case 'a':Tenprintf"option:%c\n", opt); One Break; A Case 'b': -printf"optarg1:%s\n", optarg); - Break; the Case 'C': -printf"optarg2:%s\n", optarg); - Break; - Case '?': +printf"unknown option:%c\n", optopt); - Break; + } A } at for(; optind<argc;optind++) -printf"argument:%s\n", Argv[optind]); -Exit0); -}
Compiling Gcc-o getopt getopt.c
Run for the first time./getopt-a-B "I am OK"-C
Results
Option:a
Optarg1:i am OK
OPTARG2: (NULL)
Run the second time./getopt-a-B "I am OK"-C "I am OK"
Results
Option:a
Optarg1:i am OK
Optarg2:i AM OK
Getopt () function