How to Use the getopt () function to parse parameters?

Source: Internet
Author: User

How to Use the getopt () function to parse parameters?

In the process of writing a program recently, part of the time is spent on Processing Parameters by the program. I heard from students about the getopt function today and found that c has a function dedicated to parameter processing. I have queried the relevant information. Here is a brief summary.

When int main (int argc, char * argv []) (or int main (int argc, char ** argv) is used, the system will introduce the user-input parameters into the program through argc and argv. argc is the number of parameters, argv is the pointer array pointing to the parameters, and the first parameter is the program file name.

Here we use getopt ()The function processes the input parameters. getopt () is located in the unistd. h system header file. The function prototype can be found in man. You can use the following command to view the man manual of getopt.

man 3 getopt

The getopt function is prototype as follows:

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

Here, we will reference IBM's explanation of it. The original Article is here. I made some changes to some of the errors,

Given the number of command parameters (argc), The array pointing to these parameters (argv) And the option string (optstring,getopt()The first option is returned and some global variables are set. When you call this function again with the same parameters, it returns the next option and sets the corresponding global variable. If no recognized options are available-1.

getopt()The global variables set include:

Extern char * optarg; // parameter pointer of the option
Extern int optind, // when getopt is called next time, check the option again from the position where optind is stored.
Extern int opterr, // when opterr = 0, getopt does not output an error message to stderr.
Extern int optopt; // when the command line option character is not included in optstring or the option lacks necessary parameters, this option is stored in optopt, and getopt returns '? '

For each option, the option string (optstring. The option with parameters is followed by:Character. If an option is followed by two colons (:), it indicates that the option and the parameter are not separated by spaces;

Can be called repeatedlygetopt()Until it returns-1Any remaining command line parameters are generally considered as file names or other content corresponding to the program.

We know that General Program Options are divided into two types: those with and without association values,

When parsing parameters, we want to find the options and options associated values from the heap parameters for us to use, and find other parameters for our call.

Getopt implements this perfectly.

During the test, we defined a global variable to store the parameter values,

Typedef struct parameter {int a; // parameter a int B; // parameter B char * B _pri; // The associated value of parameter B int c; // parameter c char * c_pri; // correlation value of parameter c} par;

If you encounter other options,getopt()An error message will be displayed, and the program will exit after the method message is displayed. Therefore, optString should be

static const char *optstring = "ab:c::?";

Before running the program, initialize the parameter and set its initial value.

// Initialize opt. a = 0; opt. B = 0; opt. B _pri = NULL; opt. c = 0; opt. c_pri = NULL;

Next, we simply use getopt to process the parameters, and finally output the final parameters. Let's take a look at our test program.

1 # include <stdio. h> 2 # include <stdlib. h> 3 # include <unistd. h> 4 5 typedef struct parameter 6 {7 int a; // parameter a 8 int B; // parameter B 9 char * B _pri; // correlation value of parameter B 10 int c; // parameter c11 char * c_pri; // correlation value of parameter c 12} par; 13 14 15 int main (int argc, char ** argv) 16 {17 int I; // loop variable 18 par opt; // parameter 19 int flag = 0; // exit loop flag 20 21 // parameter initialization 22 opt. a = 0; 23 opt. B = 0; 24 opt. B _pri = NULL; 25 opt. c = 0; 26 opt. c_pri = NULL; 27 28 // Parameter detection 29 if (argc = 1) 30 {31 printf ("You have not set the option! \ N "); 32 exit (0); 33 34} 35 // output the unprocessed parameter 36 printf (" system input parameter :"); 37 for (I = 1; I <argc; I ++) 38 {39 printf ("% s", argv [I]); 40} 41 printf ("\ n"); 42 43 // cyclically process incoming parameter 44 while (flag! =-1) 45 {46 // call the getopt processing parameter 47 switch (getopt (argc, argv, "AB: c ::? ") 48 {49 case 'A': 50 opt. a = 1; 51 break; 52 case 'B': 53 opt. B = 1; 54 opt. B _pri = optarg; 55 break; 56 case 'C': 57 opt. c = 1; 58 opt. c_pri = optarg; 59 break; 60 case-1: 61 flag =-1; 62 break; 63 default: 64 break; 65} 66} 67 68 if (optind! = Argc) 69 {70 printf ("the non-program options in the parameter are:"); 71 for (I = optind; I <argc; I ++) 72 {73 printf ("% s \ t", argv [I]); 74} 75 printf ("\ n "); 76} 77 78 // output parsing result 79 printf ("the options enabled after parsing to program startup are:"); 80 if (opt. a = 1) 81 printf ("a,"); 82 if (opt. B = 1) 83 printf ("B (parameter: % s),", opt. B _pri); 84 if (opt. c = 1) 85 printf ("c (parameter: % s),", opt. c_pri); 86 printf ("\ n"); 87 88 89 // after processing, all output parameters are compared with the original 90 printf ("after getopt is used, the system parameter is changed: "); 91 for (I = 1; I <argc; I ++) 92 {93 printf (" % s ", argv [I]); 94} 95 printf ("\ n"); 96 97 return 0; 98}

After saving, compile and run.

$. /. Out-a-B 123 3 22-h-c1:-a-B 123 3 22-h-c1. /. out: invalid option -- the 'H' parameter has the following non-Program Options: 3 22. The options enabled after parsing to the program startup are: a, B (parameter: 123 ), c (parameter: 1). After getopt is used, the system parameter is changed to-a-B 123-h-c1 3 22.

The input parameters are all parsed, and the "-h" option is displayed directly. If you do not want abnormal parameters to be displayed, or you want to handle them yourself, you can set the global variable opterr = 0 in getopt. Do not add it when optstring is used ?, For example

opterr = 0;static const char *optstring = "ab:c::";

Will the program return an unknown option after detecting it ?, We can handle it like this

Opterr = 0; // getopt does not output the error parameter... other program sections... // process the passed parameter while (flag! =-1) {// call the getopt processing parameter switch (getopt (argc, argv, "AB: c:") {case 'A': opt. a = 1; break; case 'B': opt. B = 1; opt. B _pri = optarg; break; case 'C': opt. c = 1; opt. c_pri = optarg; break; case '? ': Printf ("abnormal options: % c \ n", optopt); break; case-1: flag =-1; break; default: break ;}}

The program source code is as follows:

1 # include <stdio. h> 2 # include <stdlib. h> 3 # include <unistd. h> 4 5 typedef struct parameter 6 {7 int a; // parameter a 8 int B; // parameter B 9 char * B _pri; // correlation value of parameter B 10 int c; // parameter c 11 char * c_pri; // correlation value of parameter c 12} par; 13 14 15 int main (int argc, char ** argv) 16 {17 int I; // loop variable 18 par opt; // parameter 19 int flag = 0; // exit loop flag 20 21 // parameter initialization 22 opt. a = 0; 23 opt. B = 0; 24 opt. B _pri = NULL; 25 opt. c = 0; 26 opt. c_pr I = NULL; 27 opterr = 0; // getopt does not output error parameter 28 29 // parameter detection 30 if (argc = 1) 31 {32 printf ("You have no options! \ N "); 33 exit (0); 34 35} 36 // output unprocessed parameter 37 printf (" system input parameter :"); 38 for (I = 1; I <argc; I ++) 39 {40 printf ("% s", argv [I]); 41} 42 printf ("\ n"); 43 44 // cyclically process input parameter 45 while (flag! =-1) 46 {47 // call the getopt processing parameter 48 switch (getopt (argc, argv, "AB: c:") 49 {50 case 'A ': 51 opt. a = 1; 52 break; 53 case 'B': 54 opt. B = 1; 55 opt. B _pri = optarg; 56 break; 57 case 'C': 58 opt. c = 1; 59 opt. c_pri = optarg; 60 break; 61 case '? ': 62 printf ("abnormal options: % c \ n", optopt); 63 break; 64 case-1: 65 flag =-1; 66 break; 67 default: 68 break; 69} 70} 71 72 if (optind! = Argc) 73 {74 printf ("the non-program options in the parameter are:"); 75 for (I = optind; I <argc; I ++) 76 {77 printf ("% s \ t", argv [I]); 78} 79 printf ("\ n "); 80} 81 82 // output parsing result 83 printf ("OPTIONS enabled after parsing to program startup are:"); 84 if (opt. a = 1) 85 printf ("a,"); 86 if (opt. B = 1) 87 printf ("B (parameter: % s),", opt. B _pri); 88 if (opt. c = 1) 89 printf ("c (parameter: % s),", opt. c_pri); 90 printf ("\ n"); 91 92 93 // after processing, all output parameters are compared with the original 94 printf ("after getopt is used, the system parameter is changed: "); 95 for (I = 1; I <argc; I ++) 96 {97 printf (" % s ", argv [I]); 98} 99 printf ("\ n"); 100 101 return 0; 102}

In this case, the running result of the same parameter is as follows:

$. /. Out-a-B 123 3 22-h-c1:-a-B 123 3 22-h-c1: the non-program options in the h parameter are: 3 22 The OPTIONS enabled after parsing to the program startup are: a, B (parameter: 123), c (parameter: 1 ), after getopt is used, the system parameter is changed to-a-B 123-h-c1 3 22.

Okay. In fact, there is another better option than getopt, that is, getopt_long, which supports long options. Because this blog post is for getopt, I will not introduce it much, you can check man's manual or wait for the next update.


Meaning of parameters in the getopt Function

Here char ** argv is a pointer array that stores the words in the command line you entered. int argc stores the number of words. For example, if you input copy file1 file2, there is 3 in argc, and argv stores the pointer to the three strings, it is an array with three pointer elements {"copy", "file1", "file2 "}.

Usage of the "optional parameters" function of getopt_long () in linux

Since your parameter is optional (: :), there must be no space between option and value as required. Functions such as getopt cannot be implemented.

To achieve this goal, you can write one by yourself. It is not very difficult.
Because there are many similar implementations available. Find one on the Internet.

You can also download the example of getopt_long attached to this document. I have seen it. Meet your needs.

Www.ibm.com/..t.html

Download it for you. For more information, see attachment.


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.