getopt is a function of getting program startup parameters under Linux#include <unistd.h>
int getopt (int argc, char * const argv[],
const char *optstring);
extern char *optarg;
extern int Optind, opterr, optopt; using the global Parameters Optarg, Optind,opterr, optopt, where Optarg is used to save the parsed option parameters below is an example of # include < Stdio.h>
#include <stdlib.h>
#include <unistd.h>
using namespace Std;
int main (int argc, char** argv)
{
int opt = 0;
while ( -1! = (opt = getopt (argc, argv, "N:t:kl")))
{
Switch (OPT)
{
Case ' n ':
fprintf (stdout, "n:%s\n", Optarg);
Break
Case ' t ':
fprintf (stdout, "t:%s\n", Optarg);
Break
Case ' K ':
fprintf (stdout, "K option get\n");
Break
Case ' l ':
fprintf (stdout, "l option get\n");
Break
}
}
return 0;
This code is intended to parse the command options with parameters and no parameters, where N and T and with parameters, K and L are not parameters, getopt is distinguished by identifying the format of the third argument, and N and T are followed by a colon, which means that the option has parameters, K and L do not. Test this code for parsing of compliant command lines and non-conforming command-line parsing smi/project/bm3.5/smi/test/zd/self>tg-n 100-t vi-k 30-l 80
n:100
T:vi
K option Get
L option Get
Smi/project/bm3.5/smi/test/zd/self>tg-n 100-t Vi-k-L
n:100
T:vi
K option Get
L option Get
Smi/project/bm3.5/smi/test/zd/self>tg-n 100-t-k-l
n:100
T:-k
L option Get
Smi/project/bm3.5/smi/test/zd/self>tg-n
Tg:option requires an argument--n
Smi/project/bm3.5/smi/test/zd/self>tg-n-T
N:-tsmi/project/bm3.5/smi/test/zd/self>tg-o-N 100
Tg:invalid option--O
N:100 can be seen, the resolution is not satisfactory, in the K and L with redundant parameters when there is no error, this can also be understood, but in the N and T command with less parameters should be an error, rather than the following command as a parameter to parse. The extra o command error or processing is correct. This command is more convenient to use, but has some limitations.
Getopt Use Example