Wednesday, June 29, 2016

Command Line Argument Processing

This is another in my series of "simple programming techniques I don't want to keep reinventing."

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

int main(int argc, char**argv)
{
  opterr = 0; /* disable auto error reporting */
  char opt = 0;
  /* These copies are needed because optind and optarg aren't
     necessarily visible to debuggers, and you often want them. */
  int myoptind = 1;
  char* myoptarg = 0;

  int a = 0;
  const char* b = 0;

  while (((char) -1) != (opt = (char) getopt(argc, argv, "ab:"))){
    myoptind = optind;
    myoptarg = optarg;

    switch(opt){

    case 'a':
      a = 1;
      break;

    case 'b':
      b = myoptarg;
      break;

    default:
      {
        char erropt = optopt;
        fprintf(stdout, "unrecognized option '%c'\n", erropt);
      }
      break;
    }
  }

  if (myoptind < argc){
    fprintf(stdout, "unused arguments:");
    while (myoptind < argc){
      fprintf(stdout, " %s", argv[myoptind++]);
    }
    fprintf(stdout, "\n");
  }

  fprintf(stdout, "a: %d\nb: %s\n", a, b);
  fflush(stdout);
  return 0;
}