/*************************************** ******************************
* Function: Test getopt
* Author: Samson
* Date: 11/30/2011
* Test Platform:
* GNU Linux version 2.6.29.4
* GCC version 4.4.0 20090506 (Red Hat 4.4.0-4) (GCC)
**************************************** ****************************/
# Include <unistd. h>
# Include <stdlib. h>
# Include <stdio. h>
Int
Main (INT argc, char * argv [])
{
Int flags, OPT;
Int nsecs, tfnd;
Nsecs = 0;
Tfnd = 0;
Flags = 0;
While (OPT = getopt (argc, argv, "N: T: C "))! =-1)
{
Switch (OPT)
{
Case 'N ':
Flags = 1;
Printf ("case n optarg is % s \ n", optarg );
Break;
Case 'T ':
Nsecs = atoi (optarg );
Printf ("Case T optarg is % s \ n", optarg );
Tfnd = 1;
Break;
Case 'C ':
Printf ("cast C is there \ n ");
Break;
Default :/*'? '*/
Fprintf (stderr, "Usage: % s [-T nsecs] [-N] Name \ n ",
Argv [0]);
Exit (exit_failure );
}
}
Printf ("Flags = % d; tfnd = % d; optind = % d \ n", flags, tfnd, optind );
If (optind> = argc)
{
Fprintf (stderr, "Expected argument after options \ n ");
Exit (exit_failure );
}
Printf ("name argument = % s \ n", argv [optind]);
// Printf parameter reorder by getopt
For (OPT = 0; opt <argc; opt ++)
{
Printf ("argv [% d] is % s \ n", opt, argv [opt]);
}
/* Other Code omitted */
Exit (exit_success );
}
In the above test procedure, when getopt is used, the parameter list is sorted according to the third parameter rule in the getopt function, for example, "N: T: C" in the test, the parameter must be-N parameter-t parameter-C without a parameter. If you enter :. /. out-C hahah-T 23-N yygy, Which is sorted by getopt. /. out-c-t 23-N yygy hahahah, the program test output is:
Cast C is there
Case T optarg is 23
Case N optarg is yygy
Flags = 1; tfnd = 1; optind = 6
Name argument = hahah
Argv [0] is./A. Out
Argv [1] is-C
Argv [2] is-T
Argv [3] is 23
Argv [4] is-n
Argv [5] Is yygy
Argv [6] Is hahah