#include <libgen.h> // needed for basename()
#include <getopt.h>
#include <stdio.h>
#include <stdlib.h>


static struct option option_list[] =
{

/* Format:
 *  1) long name (invoked with --[arg])
 *  2) # of subarg for the arg
 *  3) if NULL, getopt_long returns '4)'.  Else,
 *      arg is a pointer that receives the value
 *  4) actual value returned by getopt_long()
 */
    {"foo", 1, NULL, 'f'},
    {"bar", 1, NULL, 'b'},
    {"switch", 0, NULL, 's'},
    {0, 0, 0, 0}
};


/* Format:
 *  make a list of the option letter (as above) with a colon
 *   if the option has a sub-arg
 */
#define OPTSTRING "f:b:s"

void usage(char* prog_name)
{

    printf ("%s: Copyright 200x, Foobar Corp. by Matt Walsh\n\n", basename (prog_name));
    printf ("Usage:\n");


   printf(" -f / --foo <arg> == invoke foo mode with 'arg'\n");
   printf(" -b / --bar <arg> == execute bar command with 'arg'\n");
   printf(" -s               == turns on the 's' switch.\n");
   printf(" -?               == shows this usage\n");

}

/* Normally one would pass in some kind of option structure so
 *  that this function can communicate the results back to the main
 *  program
 */
int parse_command_line (int argc, char **argv)
{
   long ch;
   int done = 0;
   int option_index = 0;
   int retVal = 0; // assume success
   int nothing_happened = 1;

   char* prog_name = argv[0];

   while(!done) // loop thru args
   {
      /* Snatch the next option.  Quit if all done.
       */
      if ((ch = getopt_long (argc, argv,
            OPTSTRING, option_list, &option_index)) < 0)

      {
         break;
      }


      if (ch == 'f')
      {  printf("foo mode enabled with arg '%s'\n", optarg);
         nothing_happened = 0;
      }

      else if (ch == 'b')
      {  printf("bar mode enabled with arg '%s'\n", optarg);
         nothing_happened = 0;
      }

      else if (ch == 's')
      {  printf("switch 's' enabled\n");
         nothing_happened = 0;
      }

      else if (ch == '?')
      {  usage(prog_name);
         nothing_happened = 0;
         return 0;
      }
      else
      {  usage(prog_name);
         nothing_happened = 0;
         printf ("unhandled option '%li'\n", ch);
         return 0;
      }
   }
   if (nothing_happened)
   {  usage(prog_name);
   }

   return 1; // SUCCESS!
}


int main(int argc, char** argv)
{
   if (!parse_command_line(argc, argv))
   {  // failed to handle cmd line args, or user wanted usage
      return 1;
   }
}


-- Main.MattWalsh - 23 May 2002
Topic revision: r1 - 23 May 2002 - MattWalsh
 
This site is powered by the TWiki collaboration platformCopyright © 2008-2012 by the contributing authors. All material on this collaboration platform is the property of the contributing authors.
Ideas, requests, problems regarding TWiki? Send feedback