Monday, April 7, 2008

getopt \ getopts for C++

Wrote a small function/class GetOpts for parsing the command line arguments (*argv[]/**argv) in C++.

Feel free to use it!

Src code can be downloaded at: [http://tomaranand.googlepages.com/getopts.tar.gz]

Below is a sample program that uses getopts.h


#include <stdio.h>

#include "getopts.h"

 

/*

* Sample runs

* ./main -h

* ./main --help

* ./main -d -c /root/google-adapter.conf

* ./main --debug --conf /root/google-adapter.conf

*/

 

int main(int argc, char *argv[])

{

    char* debug = NULL;

    char* conf = NULL;

    struct options opts[] = 

    {

       { &debug, "debug", "Set Debug", "d", 0 },

       { &conf, "conf", "Path to Configuration File", "c", 1 }

    };

 

    GetOpts _optprser = GetOpts(opts, 2, argc, argv);

    

    if(debug != NULL) {

        printf("debug is set\n");

        delete debug;

    }

    if(conf != NULL) {

        printf("Value for conf is: %s\n", conf);

        delete [] conf;

    }

    return 0;

}



Here is the header file getopts.h:



#ifndef GETOPTS_H

#define GETOPTS_H

 

struct options

{

    char **vartoset;    //Address to the variable that will hold the value

    char *name;        //Full name of the parameter

    char *descp;    //Text description of the parameter

    char *sname;    //Short name of the parameter

    int value;        //1or0 0 if has no value (true/false) 1 if is going to have value

};

 

class GetOpts

{

    public:

        GetOpts(struct options [], int, int, char* []);

    private:

        void usage(char *, int, struct options []);

};

 

#endif    /*GETOPTS_H*/

1 comments:

Admin said...

Hi Anand,
did you try getopt_pp?

You may find it useful:
http://code.google.com/p/getoptpp/

Daniel.