The getopt function
int getopt(int argc, char * const argv, const char *optstring);
extern char *optarg;
extern int optind, opterr, optopt;
The getopt function is used to parse command option. The parameters argc and argv are the argument count and argument array as passed to the “command”. The argument optstring is a string of recognized option characters; if a character is followed by a colon, the option takes an argument.
The variable optind is the index of the next element of the argv vector to be processed. It shall be initialized to 1 by the command routine, and getopt() shall update it when it finishes with each element of argv. When an element of argv contains multiple option characters, it is unspecified how getopt() determines which options have already been processed.
The getopt() function shall return the next option character (if one is found) from argv that matches a character in optstring, if there is one that matches. If the option takes an argument, getopt() shall set the variable optarg to point to the option-argument.
If getopt() encounters an option character that is not contained in optstring, it shall return the question-mark ( '?' ) character. If it detects a missing option-argument, it shall return the colon character ( ':' ) if the first character of optstring was a colon, or a question-mark character ( '?' ) otherwise. In either case, getopt() shall set the variable optopt to the option character that caused the error. If the application has not set the variable opterr to 0 and the first character of optstring is not a colon, getopt() shall also print a diagnostic message to stderr in the format specified for the getopts utility.
The getopt() function isn't reentrant. The getopt() function shall return the next option character specified on the command line.
A colon ( ':' ) shall be returned if getopt() detects a missing argument and the first character of optstring was a colon ( ':' ). A question mark ( '?' ) shall be returned if getopt() encounters an option character not in optstring or detects a missing argument and the first character of optstring was not a colon ( ':' ). Otherwise, getopt() shall return -1 when all command line options are parsed.
The argv and argc parameters can be built using the function iCreateCommandLine:
The function builds the argv list from the pcCmdLine and returns the number of parsered "arguments" (the argc). The maximum number of arguments is defined by the macro MAX_CMD_LINE_ARGS (the default is 5). The argv variable is the global variable pcArgv defined by :
char * pcArgv[MAX_CMD_LINE_ARGS+1];
The synopsys of the function is :
int iCreateCommandLineArgs(char * pcCmdLine)
where pcCmdLine is the string that will be parsered.
Note : this function will change the pcCmdLine .
(to be continued…)