24 Feb 2013

Example using getopt from C


// $Id$

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

struct opt_t {
 char* opt;
 char* arg;
};

int opt_parse(int argc, char *argv[], const char * optstring) {

 //Specifying the expected options
 //The two options l and b expect numbers as argument
 while ((option = getopt(argc, argv, optstring /*"apl:b:"*/)) != -1) {
  switch (option) {
   case 'd':
    printf("Database: %s\n", optarg);
    break;
   default: 
     printf("Huh?"); 
    return EXIT_FAILURE;
  }
 }
 
 return 0;
}

int main(int argc, char** argv) {
 const char* opts = "d:";
 
 int r = opt_parse(argc, argv, opts);
 
 return r;
}