/* * Simple commandline argument processing function * Programmed and designed by Matti 'ccr' Hamalainen * (C) Copyright 2002-2004 Tecnic Software productions (TNSP) * * Please read file 'COPYING' for information on license and distribution. */ #include "th_args.h" #include "th_util.h" #include #include /* Process arguments, handling short and long options by * calling the given callback functions. */ void th_processArgs(int argc, char *argv[], t_opt optList[], int optListN, void (*handleOpt)(int, char *, char *), void (*handleFile)(char *)) { BOOL endOptions; int argIndex, newArgIndex, optLen, optN, i; char *currArg, *optArg; /* Parse arguments */ argIndex = 1; endOptions = FALSE; while (argIndex < argc) { currArg = argv[argIndex]; if ((currArg[0] == '-') && !endOptions) { newArgIndex = argIndex; if (currArg[1] == '-') { /* Check for "--", which ends the options-list */ if (currArg[2] == 0) { endOptions = TRUE; continue; } /* Long option */ optN = -1; optLen = 0; for (i = 0; (i < optListN) && (optN < 0); i++) { optLen = strlen(optList[i].longOpt); if (strncmp(&currArg[2], optList[i].longOpt, optLen) == 0) optN = i; } if ((optN >= 0) && (optList[optN].hasArg)) { if (currArg[optLen + 2] == '=') optArg = &currArg[optLen + 3]; else optArg = NULL; } else optArg = NULL; /* Call handler function */ handleOpt((optN >= 0) ? optList[optN].optID : -1, optArg, currArg); } else { /* Short options */ currArg++; while (*currArg) { for (optN = 0; (optN < optListN); optN++) if (*currArg == optList[optN].shortOpt) { if (optList[optN].hasArg) optArg = argv[++newArgIndex]; else optArg = NULL; handleOpt(optList[optN].optID, optArg, currArg); } currArg++; } } argIndex = newArgIndex; } else { /* Was not option argument */ handleFile(currArg); } argIndex++; } } void th_showHelp(FILE *outFile, t_opt optList[], int optListN, char *progName, char *progUsage) { int i; char tmpStr[64]; fprintf(outFile, "\n%s v%s (%s)\n" "%s\n" "%s\n" "Usage: %s %s\n", th_prog_name, th_prog_version, th_prog_fullname, th_prog_author, th_prog_license, progName, progUsage); for (i = 0; i < optListN; i++) { if (optList[i].shortOpt) fprintf(outFile, " -%c, ", optList[i].shortOpt); else fprintf(outFile, " "); if (optList[i].longOpt) { if (optList[i].hasArg) { snprintf(tmpStr, sizeof(tmpStr), "%s=ARG", optList[i].longOpt); fprintf(outFile, "--%-15s", tmpStr); } else fprintf(outFile, "--%-15s", optList[i].longOpt); } else fprintf(outFile, " "); fprintf(outFile, " %s.\n", optList[i].optDesc); } }