C language Getopt () function

Source: Internet
Author: User

Related function header file #include <unistd.h>
Defining Functions int getopt (int argc,char * CONST argv[],const char * optstring);
Function description

The argc and argv parameters of the function are usually passed directly from the parameters of Main (). Optstring is a string of option letters. If any of the characters in the string are followed by a colon, then this option requires an option parameter. when given the number of getopt () command Arguments (), the argc array () that points to these parameters, argv and the option string ( optstring ), the getopt() first option is returned, and a number of global variables are set. When the function is called again with the same parameters, it returns the next option and sets the corresponding global variable. If no more recognizable options are returned -1 , the task is completed. The getopt() global variables that are set include:
    • char *optarg--The current option parameter string (if any).
    • int optindThe current index value of the--ARGV. When Getopt () is used in a while loop, the remaining strings are treated as operands when the loop ends, and can be found in argv[optind] to argv[argc-1].
    • int opterr--This variable is nonzero, the getopt () function is "invalid option" and "Missing parameter option, and outputs its error message."
    • int optopt--When an invalid option character is found, the getopt () function or return '? ' character, or return ': ' character, and Optopt contains the found invalid option character.

getopt () is used to parse command-line arguments. The parameters argc and argv are the number and contents of the arguments passed by main (). The parameter optstring represents the option string to be processed. This function returns the next option letter in argv, which corresponds to the letter in the parameter optstring. If the letter in the option string is followed by the colon ":", then there are related arguments, and the global variable, OPTARG, points to this extra parameter. If getopt () does not find a matching parameter, it prints an error message and sets the global variable optopt to "?". Character, if you do not want getopt () to print the error message, simply set the global variable Opterr to 0.   definition of short parametersgetopt () uses a string referred to by optstring as a short argument list, like "1ac:d::" is a short argument list. The definition of a short parameter is a '-' followed by a letter or number, like-A,-B is a short argument. Each number or letter defines a parameter. The short parameters are divided into three types in the getopt definition:1. A parameter without a value, which is defined as the parameter itself. 2. Must have a value parameter, which is defined by adding a colon after the parameter itself. 3. An optional value parameter, which is defined by adding two colons after the parameter itself. take the above "1AC:D:" as a sample to illustrate, where the 1,a is a parameter without value, C is a parameter that must take a value, D is an optional value of the parameter. in the actual call, ' -1-a-C cvalue-d ', ' -1-a-C cvalue-ddvalue ', ' -1a-ddvalue-c cvalue ' are all legal. Here are three points to note:1. Parameters without values can be ligatures, like 1 and a are parameters without values, they can be -1-a separately, or they can be -1a or-a1 ligatures. 2. The parameters are not in order, ' -1a-c cvalue-ddvalue ' and '-d-c cvalue-a1 ' parse result is the same. 3. Note that there can be no space between the value of an optional value parameter and the parameter, which must be written in a format such as-ddvalue, which resolves the error if written in the format of-D dvalue.
return value getopt () Each call returns the arguments passed in at a command line at a time.  Getopt () returns 1 when there is no last call to the parameter.   When parsing to a parameter that is not inside the optstring, or if a required value parameter does not have a value, return '? '. When Optstring starts with ': ', it returns ': ' Instead of '? ' in the case of a missing value parameter.

If you do not want to output any error messages, or you prefer to export custom error messages. You can change the error message output behavior of the getopt () function in the following two ways:
    1. Before calling Getopt (), set Opterr to 0 so that you can force it to output no messages when the getopt () function finds an error.
    2. If the first character of the optstring parameter is a colon, then the getopt () function remains silent and returns different characters depending on the error condition, as follows:
      • "Invalid option"--getopt () returns '? ', and Optopt contains invalid option characters (this is normal behavior).
      • "Missing option parameter"--getopt () returns ': ' If the first character of optstring is not a colon, then getopt () returns '? ', which makes this case not separate from the case of invalid options.

Examples are as follows:
#include <stdio.h> #include <unistd.h>int main (int Argc,char *argv[]) {  int ch;  opterr=0;    while ((Ch=getopt (ARGC,ARGV, "A:B::CDE")!=-1)  {    printf ("optind:%d\n", optind);    printf ("optarg:%s\n", optarg);    printf ("ch:%c\n", ch);    Switch (CH)    {case      ' a ':        printf ("Option A: '%s ' \ n", optarg);        break;      Case ' B ':        printf ("Option B: '%s ' \ n", optarg);        break;      Case ' C ':        printf ("option c\n");        break;      Case ' d ':        printf ("option d\n");        break;      Case ' E ':        printf ("option e\n");        break;      Default:        printf ("Other option:%c\n", ch);    }    printf ("optopt+%c\n", optopt);}  }    

After compiling with GCC, execute the above command on the terminal line:./a.out-a1234-b432-c-D will have the following output: Optind:2optarg:1234ch:aoption A: ' 1234 ' optopt+optind:3optarg : 432ch:boption B: ' 432 ' Optopt+optind:4optarg: (null) ch:coption Coptopt+optind:5optarg: (null) ch:doption doptopt+

Reference documents:
http://vopit.blog.51cto.com/2400931/440453
http://blog.csdn.net/mr_jj_lian/article/details/6835137

C language Getopt () function

Related Article

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.