Linux-c getopt () parameter handling function

Source: Internet
Author: User

Transferred from: https://www.cnblogs.com/qingergege/p/5914218.html

Recently in the Linux C programming, undergraduate time did not study well, hope to learn younger brothers learn lesson.

Well, it's a bit verbose, but it's really a piece of advice. Step into the chase:

Our protagonist----the getopt () function.

Heroes do not ask the source, getopt () function is the source of the Unistd.h header file (haha), write the code when you must not forget to put his old include on.

And look at this guy's prototype (not six-ear macaques):

int getopt (int argc,char * CONST argv[],const char * optstring);

First two parameters everyone will not be unfamiliar, yes, the eldest brother main function of two parameters! The boss passed in the parameters of nature to be someone next!

The third argument is a string, look at the name, we can call him the option string (explained later)

The return value is type int, we all know that the char type can be converted to int type, each character has his corresponding integer value, in fact, this return value is a character, what character, called the option character (let's call it, later will explain)

A simple look at the origins and prototypes, let's see what this guy is capable of!

(⊙o⊙) ... Before that, I'd like to introduce some of his brothers. ~ ~ Uh, uh,

Younger brother 1, extern char* Optarg;

Little brother 2, extern int optind;

Little brother 3, extern int opterr;

Little brother 4, extern int optopt;

It's a good line. Little Brother 1 is used to save the parameters of the option (first mix face ripe, followed by examples); the younger brother 2 is used to record the next search position; the younger brother 3 indicates whether the error message is output to stderr, 0 means no output, younger brother 4 is not the option in the option string optstring (a bit messy, There will be examples later)

Begin to explain the problems left over.

Question 1: What the hell is an option?

Under Linux Everyone has used such an instruction: gcc helloworld.c-o helloworld.out; The-O in this directive is the command-line option, and the following helloworld.out is the parameter that is carried by the-o option. Of course people familiar with the shell instructions know (although I am not familiar with), some options are not with parameters, and so the option without parameters can be written together (this point in the following example will be used, want to understand), for example, there are two options-C and-D, these two options are not parameters (and obviously a good base friend), Then they can be written together and written in-CD. The actual example: when we delete a folder can use the command RM directory name-RF, originally-R for recursive deletion, that is, delete all the contents of the folder,-F means to delete immediately without prompting, they both do not have parameters, then they can write together.

Question 2: Where is the option string sacred?

Let's see an example.

"A:b:cd::e", this is an option string. corresponding to the command line is-A,-B,-C,-D,-E. What is a colon? A colon indicates a parameter, and a colon indicates that the option must be followed by an argument (without parameters), but this parameter can be written together with the options, or separated by spaces, such as-a123 and-a 123 (with spaces in the middle) indicating that 123 is the parameter of-a ; Two colons means that the parameter of this option is optional, that is, you can have parameters, or you can have no parameters, but to be aware of parameters, there can be no space between the parameters and options (there is a blank space will be an error, OH), this and a colon when there is a difference.

OK, give me the code first, and then explain it.

#include <unistd.h> #include <stdio.h>int main (int argc, char * argv[]) {int ch;    printf ("\ n");    printf ("optind:%d,opterr:%d\n", Optind,opterr);       printf ("--------------------------\ n");           while (ch = getopt (argc, argv, "Ab:c:de::"))! =-1) {printf ("Optind:%d\n", optind);                          Switch (CH) {case ' a ': printf ("with option:-a\n\n");               Break                        Case ' B ': printf ("with option:-b\n");                       printf ("The argument of-b is%s\n\n", optarg);               Break                       Case ' C ': printf ("with option:-c\n");                       printf ("The argument of-c is%s\n\n", optarg);               Break                     Case ' d ': printf ("with option:-d\n");              Break                    Case ' E ': printf ("with option:-e\n"); PrintF ("The argument of-e is%s\n\n", optarg);              Break                       Case '? ': printf ("Unknown option:%c\n", (char) optopt);               Break }       }}

Post-compilation Command line execution: #./main-b "Qing er"

The output is:

Optind:1,opterr:1
--------------------------
Optind:3
Have option:-B
The argument of-b is Qing er

We can see that the initial values for both Optind and Opterr are 1, and the preceding Opterr nonzero indicates that the error produced is to be output to stderr. So what is the initial value of Optind 1?

This involves the two parameters of the main function, ARGC represents the number of parameters, argv[] represents each parameter string, for the above output ARGC is 3,argv[] respectively:./main and-B and "Qing er", actually the real parameter is the second-B start, i.e. argv[1], so the initial value of Optind is 1;

When the getopt () function is executed, each command-line argument is scanned sequentially (starting with subscript 1), the first-B is an option, and this option is available in the option string optstring, and we see that B has a colon followed by B, which must be followed by a parameter, and "Qing er" That's his argument. So this command line is in line with the requirements. As to why Optind is 3 after execution, this is because Optind is the starting index for the next option search and, again, the getopt () function to start searching from argv[3]. Of course, this example argv[3] is gone, and the getopt () function returns-1.

Look at one more input:

./main-b "Qing er"-c1234

The output is:

Optind:1,opterr:1
--------------------------
Optind:3
Have option:-B
The argument of-b is Qing er

Optind:4
Have option:-C
The argument of-c is 1234

For this procedure call three times the getopt () function, as in the first input, is to find the option-B and his parameter "Qing er", when the value of Optind is 3, it means that the next time the getopt () to start the search from argv[3], so the second call getopt () function, find the option-C and his parameter 1234 (the options and parameters are joined together), because-c1234 is written together, so he takes up argv[3], so the next search starts from argv[4], and argv[4] is empty, so the third call to Getopt () The function returns-1, with the loop ending.

Next we look at a wrong command line input:./main-z 123

The output is:

Optind:1,opterr:1
--------------------------
./main:invalid option--' Z '
Optind:2
Unknown option:z

Where./main:invalid option-' Z ' is the error output to stderr. If the Opterr is set to 0 then this output will not be available.

Look at a wrong command line input:./main-zheng

Optind:1,opterr:1
--------------------------
./main:invalid option--' Z '
Optind:1
Unknown option:z
./main:invalid option--' h '
Optind:1
Unknown option:h
Optind:2
Have option:-E
The argument of-e is Ng

The previous reference to the option without parameters can be written together, so when getopt () Find-Z, found in the optstring did not, this time he thought H is an option, that is,-H and Z write together, and so on, until the Find-e, found in optstring.

Finally, getopt () will change the order of the parameters in argv[]. After multiple getopt (), the parameters of options and options in argv[] are placed in front of the array, and optind points to the position of the first non-option and parameter. See Example

#include <unistd.h> #include <stdio.h>int main (int argc, char * argv[]) {int i;    printf ("--------------------------\ n");    for (i=0;i<argc;i++) {printf ("%s\n", Argv[i]);       } printf ("--------------------------\ n");           int aflag=0, bflag=0, cflag=0;    int ch;    printf ("\ n");    printf ("optind:%d,opterr:%d\n", Optind,opterr);       printf ("--------------------------\ n");           while (ch = getopt (argc, argv, "Ab:c:de::"))! =-1) {printf ("Optind:%d\n", optind);                          Switch (CH) {case ' a ': printf ("with option:-a\n\n");               Break                        Case ' B ': printf ("with option:-b\n");                       printf ("The argument of-b is%s\n\n", optarg);               Break                       Case ' C ': printf ("with option:-c\n");              printf ("The argument of-c is%s\n\n", optarg);         Break                     Case ' d ': printf ("with option:-d\n");              Break                    Case ' E ': printf ("with option:-e\n");                  printf ("The argument of-e is%s\n\n", optarg);              Break                       Case '? ': printf ("Unknown option:%c\n", (char) optopt);               Break      }} printf ("----------------------------\ n");    printf ("optind=%d,argv[%d]=%s\n", Optind,optind,argv[optind]);    printf ("--------------------------\ n");    for (i=0;i<argc;i++) {printf ("%s\n", Argv[i]);    } printf ("--------------------------\ n"); }

Command line:./main zheng-b "Qing er" han-c123 Qing

The output is:

--------------------------
./main
Zheng
-B
Qing er
Han
-c123
Qing
--------------------------


Optind:1,opterr:1
--------------------------
Optind:4
Have option:-B
The argument of-b is Qing er

Optind:6
Have option:-C
The argument of-c is 123

----------------------------
Optind=4,argv[4]=zheng
--------------------------
./main
-B
Qing er
-c123
Zheng
Han
Qing
--------------------------

You can see that the first argv[] content is:

./main
Zheng
-B
Qing er
Han
-c123
Qing

After executing several getopt, it becomes

./main
-B
Qing er
-c123
Zheng
Han
Qing

As we can see, the options selected by Getopt and the corresponding parameters are placed in the front of the array in order, and those that are neither options nor parameters are placed in order. At this point, Optind is 4, which is a parameter that points to the first non-option and not the option, Zheng

Linux-c getopt () parameter handling function

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.