Author: gnuhpc
Source: http://www.cnblogs.com/gnuhpc/
1. getopt
# Include <unistd. h>
Extern char * optarg;
Extern int optind;
Extern int optopt;
Extern int opterr;
Extern int optreset;
Int getopt (INT argc, char * const * argv, const char * optstring );
Getopt () returns an option each time it is called. Argc and argv are obviously two parameters of the main function.
The character string optstring can contain the following elements: a single character followed by a colon, followed by an option parameter, followed by two colons, followed by a dispensable option parameter. For example, an option character "X" indicates the option "-X", an option character "X:" indicates the option and its parameter "-x argument", and an option character "X :: "indicates that the parameter of option X is optional (": "is added by GNU, not necessarily available in all UNIX systems ).
After getopt () is returned, if there is an option parameter, optarg points to the option parameter, and the variable optind contains the next argv parameter as the index for the next call of getopt. The optopt variable saves the last known option returned by getopt.
When the argument series has reached the end, the getopt () function returns-1. When an unknown option is encountered, getopt returns '? '. The option interpretation in the parameter column may be canceled by '--' because it causes getopt () to send an end signal to the parameter processing and return-1.
Most of the time, we do not want to output any error messages, or even output custom error messages. You can use the following two methods to change the error message output behavior of the getopt () function:
Before calling getopt (), set opterr to 0. In this way, you can force the getopt () function to output no messages when it finds an error.
If the first character of the optstring parameter is a colon, The getopt () function will remain silent and return different characters according to the error, as shown below:
"Invalid option"-getopt () returns '? And optopt contains invalid option characters (this is a normal behavior ).
"Option parameter missing"-getopt () returns ':'. If the first character of optstring is not a colon, getopt () returns '? ', Which makes this situation different from the case where the invalid option is used.
/* Getopt. C */
# Include <unistd. h>
# Include <stdio. h>
Int main (INT argc, char * argv [])
{
Int aflag = 0, bflag = 0, cflag = 0;
Int ch;
While (CH = getopt (argc, argv, "AB: C "))! =-1)
{
Printf ("optind: % d/N", optind );
Switch (CH ){
Case 'A ':
Printf ("have option:-A/N ");
Aflag = 1;
Break;
Case 'B ':
Printf ("have option:-B/N ");
Bflag = 1;
Printf ("the argument of-B is % s/n", optarg );
Break;
Case 'C ':
Printf ("have option:-c ");
Cflag = 1;
Break;
Case '? ':
Printf ("unknown option: % C/N", (char) optopt );
Break;
}
}
}
2. getopt_long
Int getopt_long (INT argc, char * const argv [],
Const char * optstring,
Const struct option * longopts, int * longindex );
Here we use an array of struct options, struct options longopt [].
Struct options is defined as follows:
Struct option {
Const char * Name;
Int has_arg;
Int * flag;
Int val;
};
The elements in the structure are described as follows:
Const char * Name
This is the option name, with no Dash in front. For example, "help" and "verbose.
Int has_arg
Specifies whether option parameters are available. If yes, which type of parameter is used, its value must be one of the following tables.
Symbol constant numerical meaning
No_argument 0 option no Parameter
Parameters required for the required_argument 1 option
Optional_argument 2 Option parameter optional
Int * flag
If the pointer is null, getopt_long () returns the value in the Val field of the structure. If the pointer is not null, getopt_long () will fill in the value in the Val field in the variable to which it points, and getopt_long () will return 0. If the flag is not null but no long option is found, the value of the variable to which it points remains unchanged.
Int Val
This value is the returned value when the long option is found, or the value in * flag is loaded when the flag is not null. In typical cases, if the flag is not null, Val is a real/false value, such as 1 or 0. If the flag is null, Val is usually a character constant, if the length option is the same as the short option, the character constant should be the same as the parameter of this option in optstring.
Each long option has a separate entry in the long option table, which must be filled with the correct value. The value of the last element in the array should be all 0. Arrays do not need to be sorted. getopt_long () performs linear search. However, sorting by long names makes it easier for programmers to read.
# Include <stdio. h>
# Include <getopt. h>
Int do_name, do_gf_name;
Char * l_opt_arg;
Static const char * shortopts = "L: NG ";
Struct option longopts [] = {
{"Name", no_argument, null, 'n '},
{"Gf_name", no_argument, null, 'G '},
{"Love", required_argument, null, 'L '},
{0, 0, 0, 0 },
};
Int main (INT argc, char * argv [])
{
Int C;
While (C = getopt_long (argc, argv, shortopts, longopts, null ))! =-1)
{
Switch (c)
{
Case 'N ':
Printf ("My name is lyr./N ");
Break;
Case 'G ':
Printf ("Her name is BX./N ");
Break;
Case 'l ':
Rochelle opt_arg = optarg;
Printf ("Our love is % s! /N ", l_opt_arg );
Break;
}
}
Return 0;
}
Case study:
/* getopt_demo - demonstrate getopt() usage * * This application shows you one way of using getopt() to * process your command-line options and store them in a * global structure for easy access. */#include <stdio.h>#include <stdlib.h>#include <unistd.h>/* doc2html supports the following command-line arguments: * * -I - don't produce a keyword index * -l lang - produce output in the specified language, lang * -o outfile - write output to outfile instead of stdout * -v - be verbose; more -v means more diagnostics * additional file names are used as input files * * The optString global tells getopt() which options we * support, and which options have arguments. */struct globalArgs_t { int noIndex; /* -I option */ char *langCode; /* -l option */ const char *outFileName; /* -o option */ FILE *outFile; int verbosity; /* -v option */ char **inputFiles; /* input files */ int numInputFiles; /* # of input files */} globalArgs;static const char *optString = "Il:o:vh?";/* Display program usage, and exit. */void display_usage( void ){ puts( "doc2html - convert documents to HTML" ); /* ... */ exit( EXIT_FAILURE );}/* Convert the input files to HTML, governed by globalArgs. */void convert_document( void ){ printf("InputFiles:%d/n",globalArgs.numInputFiles); /* ... */}int main( int argc, char *argv[] ){ int opt = 0; /* Initialize globalArgs before we get to work. */ globalArgs.noIndex = 0; /* false */ globalArgs.langCode = NULL; globalArgs.outFileName = NULL; globalArgs.outFile = NULL; globalArgs.verbosity = 0; globalArgs.inputFiles = NULL; globalArgs.numInputFiles = 0; /* Process the arguments with getopt(), then * populate globalArgs. */ opt = getopt( argc, argv, optString ); while( opt != -1 ) { switch( opt ) { case 'I': globalArgs.noIndex = 1; /* true */ break; case 'l': globalArgs.langCode = optarg; break; case 'o': /* This generates an "assignment from * incompatible pointer type" warning that * you can safely ignore. */ globalArgs.outFileName = optarg; break; case 'v': globalArgs.verbosity++; break; case 'h': /* fall-through is intentional */ case '?': display_usage(); break; default: /* You won't actually get here. */ break; } printf("optind=%d/n",optind); opt = getopt( argc, argv, optString ); } globalArgs.inputFiles = argv + optind; globalArgs.numInputFiles = argc - optind; printf("argc=%d/n",argc); printf("optind=%d/n",optind); convert_document(); return EXIT_SUCCESS;}
Author: gnuhpc
Source: http://www.cnblogs.com/gnuhpc/