1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88
|
/*
* Simple commandline argument processing function
* Programmed and designed by Matti 'ccr' Hamalainen
* (C) Copyright 2002-2003 Tecnic Software productions (TNSP)
*
* Please read file 'COPYING' for information on license and distribution.
*/
#include "th_args.h"
#include <stdio.h>
#include <string.h>
void th_processArgs(int argc, char *argv[],
t_arg argList[], int argListN,
void (*handleOpt)(int, char *, char *),
void (*handleFile)(char *))
{
int argIndex, newArgIndex, optN, i, j;
char *currArg, *optArg;
/* Parse arguments */
argIndex = 1;
while (argIndex < argc)
{
currArg = argv[argIndex];
if (currArg[0] == '-')
{
newArgIndex = argIndex;
optN = -1;
optArg = NULL;
j = 0;
if (currArg[1] == '-')
{
/* Long option */
for (i = 0; (i < argListN) && (optN < 0); i++)
{
j = strlen(argList[i].longArg);
if (strncmp(&currArg[2], argList[i].longArg, j) == 0) optN = i;
}
if ((optN > 0) && (argList[optN].hasArg))
{
if (currArg[j+2] == '=') {
optArg = &currArg[j+3];
} else {
newArgIndex = argIndex + 1;
optArg = argv[newArgIndex];
}
}
} else {
/* Short option */
for (i = 0; (i < argListN) && (optN < 0); i++)
{
if (strcmp(&currArg[1], argList[i].shortArg) == 0) optN = i;
}
if ((optN > 0) && (argList[optN].hasArg))
{
newArgIndex = argIndex + 1;
optArg = argv[newArgIndex];
}
}
/* Call handler function */
handleOpt(optN, optArg, currArg);
argIndex = newArgIndex;
} else {
/* Was not option argument */
handleFile(currArg);
}
argIndex++;
}
}
void th_showHelp(t_arg argList[], int argListN)
{
int i;
for (i = 0; i < argListN; i++)
{
fprintf(stderr, " -%-6s --%-15s %s.\n",
argList[i].shortArg, argList[i].longArg, argList[i].argDesc);
}
}
|