A simple test example of the GNU getopt Function

Source: Internet
Author: User

/*************************************** ******************************

* 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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.