Reprinted -- Use of the getopt Function

Source: Internet
Author: User

Reprinted -- Use of the getopt Function


The author writes well.

Every day you are using a large number of command line programs. Do you feel that the command line parameters are easy to use? They are all implemented using getopt.
Using getopt to write programs in Linux is cool. The following describes how to use getopt.

=== Getopt =

Before discussing parameter processing, we should clarify two concepts: Options and option parameters.
Gcc-g-o Test test. c
We often use the above command to compile the program. Here, G and O are options, and test is the option parameter of O.

Let's take a look at getopt:

First, the function declaration:
# 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 );

Let's look at an example:
/* 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;
Case 'B ':
Printf ("have option:-B \ n ");
Bflag = 1;
Printf ("the argument of-B is % s \ n", optarg );
Case 'C ':
Printf ("have option:-c ");
Cflag = 1;
Case '? ':
Printf ("unknown option: % C \ n", (char) optopt );

Through the above example, you should be able to use the getopt function in your own program.

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.
For example, if optstring Is A: B: C, it indicates that a carries a parameter, B is optional, and C is not.
If you enter D, "invalid option", getopt returns '? '
If the input a does not contain the parameter and the option parameter is missing, getopt should return ':'. If the first character of optstring is not, this error will be treated as an "invalid parameter", so that getopt will return '? '; Thus the error type cannot be differentiated

For example:
Wangyao @ fisherman :~ /Desktop/advanced Linux programming/alkaline-listings/trainning $./getopt-a-d-B foo
Optind: 2
Have option:-
./Getopt: Invalid option -- d
Optind: 3
Unknown option: d
Optind: 5
Have option:-B
The argument of-B is foo
Wangyao @ fisherman :~ /Desktop/advanced Linux programming/alkaline-listings/trainning $./getopt-a ---C-B foo
Optind: 2
Have option:-

The source code of getopt is below. getopt will only be interpreted as-.

Both the opterr and optind variables are initialized to 1. If you want to skip the first few parameters of the command line, you can set optind to another value before calling getopt.
If you do not want getopt () to output error information, set the global variable opterr to 0.

Is it easy to use!

=== Getopt_long =

I dare say that when almost everyone is in touch with a new command, the first thing we do is cmd-H or cmd -- help,-H. We all know that it is implemented using getopt, so how is -- help implemented? That is, getopt_long. It supports long parameters.

Let's first look at an example program:
# 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 ");
Case 'G ':
Printf ("Her name is BX. \ n ");
Case 'l ':
Rochelle opt_arg = optarg;
Printf ("Our love is % s! \ N ", l_opt_arg );
Return 0;

In the code, we use getopt_long to parse Long Options. 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.

Next, let's take a look at the structure in the program:
Struct option longopts [] = {
{"Name", no_argument, null, 'n '},
{"Gf_name", no_argument, null, 'G '},
{"Love", required_argument, null, 'L '},
{0, 0, 0, 0 },
The structure describes three common options: name, gf_name, and love. Love requires options. The short options are N, G, and L respectively.
Note: The third parameter flag of the struct In the struct array above is null.

Program running result:
Wangyao @ fisherman :~ /Desktop/advanced Linux programming/alkaline-listings/trainning $./getopt_long -- name
My name is lyr.
Wangyao @ fisherman :~ /Desktop/advanced Linux programming/alkaline-listings/trainning $./getopt_long-n
My name is lyr.
Wangyao @ fisherman :~ /Desktop/advanced Linux programming/alkaline-listings/trainning $./getopt_long-l me
Our love is me!
Wangyao @ fisherman :~ /Desktop/advanced Linux programming/alkaline-listings/trainning $./getopt_long -- love me
Our love is me!
Wangyao @ fisherman :~ /Desktop/advanced Linux programming/PLD-listings/trainning $

=== Reference ===
Features of the getopt () function provided by GNU


Use getopt () for Command Line Processing


=== Questions ===
1. How to specify the optional parameter in getopt?
2. Is it possible to use an option with multiple parameters, such as begin-I

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: 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.