creating command-line parser

Notice that almost all linux programs have command-line options, you can pass in the arguments to your programs. Some common arguments such as:

dummy -v
dummy --help

So there is two type of options, long and short. In linux (probably unix based os as well), we have getopt functions to help us for this. See the simple examples as bellow:

#include<stdio.h>
#include<getopt.h>

int main(int argc, char *argv[])
{
    int gnDebug=0;

    while(1)
    {
        int option_index = 0;
        int optchr;

        static struct option long_options[4] = {
            {"debug", 0,0,0},
            {"version",0,0,'v'},
            {"help",0,0,'h'},
            {0,0,0,0}
        };

        optchr=getopt_long(argc, argv ,"hvV", long_options, &option_index);
        if(optchr==-1)
            break;
        switch (optchr)
        {
            case 0:
                //if(strcmp(long_options[option_index].name,"debug")==0)
                if(option_index==0)
                {
                    if (gnDebug)
                    {
                        printf("[Debug Mode Off]\n");
                        gnDebug=0;
                    }
                    else
                    {
                        printf("[Debug Mode Set]\n");
                        gnDebug=1;
                    }
                }
                break;
            case 'v':
            case 'V':
                printf(" 0.1\n");
                return 0;
            case 'h':
                printf("Usage:\n");
                printf(" %s -v Check binary version\n",argv[0]);
                printf(" %s -h Display this help\n",argv[0]);
                return 0;
                break;
        }//end switch
    }//end while

    return 0;
}

First of all construct your long options array from option structure. First element is the long name, second element is to indicate whether the long option takes any arguments. Its like if you want to do this

dummy --debug 2

2 is an argument of long option debug. And the last element of struct is the equivalent of short option. You do not need to write twice of the execution code for the same option.

Next, call getopt_long, the third parameter is to list all short options. And the rest should be easy to understand. If you only need to specified short option, don’t use getopt_long, use getopt instead.

Reference:
http://www.gnu.org/software/libc/manual/html_node/Getopt.html

2 thoughts on “creating command-line parser

  1. Pingback: alldevnet.com

Leave a Reply

Your email address will not be published. Required fields are marked *

*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>