Argument parser

0.1

Author:
Mao Yu (http://www.mao-yu.com)
Date:
Created: Friday, May 28, 2010
Updated: Saturday, June 26, 2010
Purpose:
Argparser provides simple argument parsing functionality given command line arguments or a configuration file.
Installation:
  1. Downloads:
  2. Add header and source file to your project
Usage:
Note:
  1. Short arguments should be 1 or 2 letters.
    • Example: '-o', or config file format 'o'
  2. Long arguments needs to be longer than 3 letters and shorter than 10.
    • Example: '-one', or config file format 'one'
  3. Arguments that accept values are space delimited in command line, but '=' delimited in config file
    • Example '-type moose', or config file format 'type=moose'
  4. Unnamed arguments are arguments that are not prefixed with '-' and are not values for named arguments.
  5. Unknown arguments are arguments prefixed with '-' but are not validly added arguments.
An example program
 #include <stdio.h>
 #include "argparser.h"

 int main( int argc, char *argv[] ){
        args_addarg("a","all","Do all things",ARGVAL_NONE);
        args_addarg("v",NULL,"Set verbosity level",ARGVAL_STRING);
        args_addarg(NULL,"yo-dawg","Yo dawg",ARGVAL_STRING);
        args_addarg("h","help","Display help",ARGVAL_NONE);
        // The following will be discarded
        args_addarg(NULL,NULL,"No names!",ARGVAL_NONE);

        if( (args_parse(argc,argv) != ARGRET_OK) &&
                        (args_parsefile("./testconfig") != ARGRET_OK) )
                printf("Error occurred parsing command line.\n");
        else{
                ArgStr verbosity;
                ArgStr unnamed[3];

                if( args_check("a") )
                        printf("Doing all things!\n");
                if( verbosity = args_getnamed("v") )
                        printf("Verbosity set to %s.\n",verbosity);
                if( args_check("h") )
                        args_print();
                if( unnamed[0] = args_getunnamed(1) )
                        printf("First unnamed: %s.\n",unnamed[0]);
                if( unnamed[1] = args_getunnamed(2) )
                        printf("Second unnamed: %s.\n",unnamed[1]);
                if( unnamed[2] = args_getunnamed(3) )
                        printf("Third unnamed: %s.\n",unnamed[2]);
                args_unknown();
        }
        args_free();
 }
Running this code with this command:
argparser -a -v DEBUG hello you good people
Will show this output:
Doing all things!
Verbosity set to DEBUG.
First unnamed: hello.
Second unnamed: you.
Third unnamed: good.
See here for full API documentation.
License
This is public domain code.