C language learning - getopt()

Use of getopt for C language learning


In Linux, we often see that when executing commands, we need to input parameters. For example, the parameters rm -rf folder in -rf are input parameters, which -r are: recursive processing, processing all files and subdirectories under the specified directory together; -f is to force delete files or directories . You should also see it often when looking at open source code getopt() .

1. Introduction to getopt

getopt()method is used to parse command-line arguments, the method is provided by the Unix standard library, included in the <unistd.h> header file.

getopt()Function structure definition

#include <unistd.h>
 
int getopt(int argc, char * const argv[], const char *optstring);
 
extern char *optarg;
extern int optind, opterr, optopt;

int main(int argc, char* argv[]){
    
    
	//getopt()
}

Getopt parameter description:

  1. argc: It is the formal parameter argc of main, indicating the number of parameters
  2. argv: It is the formal parameter argv of main, which represents the string variable array of parameters
  3. optstring: option string, a letter represents a short parameter, if there is ":" after the letter, it means that this parameter must have parameters. For example "a:b:c", the program can accept parameters "-a 10 -b 1000 -c".
    Note: The short parameters are divided into three types in the definition of getopt:
    1) The parameter without value, its definition is the parameter itself.
    2) A parameter that must have a value is defined by adding a colon after the parameter itself.
    3) Parameters with optional values, which are defined by adding two colons after the parameter itself.

This is used "2ab:c::"as an example to illustrate, among which 2,aare parameters without values, bparameters that must have values, cand parameters with optional values.
In the actual call, it can be written as '-2 -a -b hello -c', or '-2 -a -b bhello -cchello', or '-2a -bhello -cchello'.
Note here:
  1) Parameters without values ​​can be written consecutively, like 2and aare parameters without values, they can be -2 -awritten separately -2aor -a2consecutively.
  2) The parameters are not in any order, '-2a -b hello -cchello'and '-b hello -cchello -a2'the analysis results of and are the same.
  3) It should be noted that there can be no spaces between the value of the optional parameter and the parameter, and it must be written in -cchellosuch a format. If it is written in -c chellosuch a format, it will cause a parsing error

Variable description:

  1. optarg: If an option has parameters, it is used to get the incoming parameter value, including the parameter string of the current option
  2. optind: the current index value of argv. When getopt() is used in a while loop, after the loop ends, the remaining strings are regarded as operands, which can be found in argv[optind] to argv[argc-1]
  3. opterr: 0 in normal operation. When non-zero, it means that there is an invalid option or a missing option parameter, and its error message is output
  4. optopt: When an invalid option character is found, the getopt() function returns either a '?' character or a ':' character, and optopt contains the found invalid option character

2. Examples

#include <stdio.h>
#include <unistd.h>
 
int main(int argc, char *argv[]) {
    
    
    int para;
    const char *optstring = "abc:d::"; // 有三个选项-abc,其中c选项后有冒号,所以后面必须有参数,d是选参
    while ((para = getopt(argc, argv, optstring)) != -1) {
    
    
        switch (para) {
    
    
            case 'a':
                printf("parameter opt is a, oprarg is: %s\n", optarg);
                break;
            case 'b':
                printf("parameter opt is b, oprarg is: %s\n", optarg);
                break;
            case 'c':
                printf("parameter opt is c, oprarg is: %s\n", optarg);
                break;
            case 'd':
                printf("parameter opt is d, oprarg is: %s\n", optarg);
                break;
            case '?':
                printf("error optopt: %c\n", optopt);
                printf("error opterr: %d\n", opterr);
                break;
        }
    }
    return 0;
}

Compile and run results:
insert image description here
analysis:

Note that when the optional parameter option -d is followed by parameters, there must be no spaces.
But if it is a mandatory parameter, that is, there is only one colon after the option, it doesn't matter whether there is a space or not.
Each call to getopt() will return the parameters passed in from the command line one by one.
  When last called with no arguments, getopt() will return -1.
  When parsing to a parameter that is not in the optstring, or a mandatory value parameter without a value, return '?'.
  When optstring starts with ':', it will return ':' instead of '?' in case of missing parameter.

recommended article

[1]https://blog.csdn.net/afei__/article/details/81261879
[2]: https://blog.51cto.com/vopit/440453
[3]: https://www.cnblogs.com/yinghao-liu/p/7123622.html
2021-09-02。。。

おすすめ

転載: blog.csdn.net/qq_36819827/article/details/120060358