I've noticed the *nix has that nice getopt function to parse the commandline arguments. So I decided to make my own windows version. Here's what I have thus far (working):
Code:
#include <stdio.h>
#include <string.h>
int cmdlineparse(int argc, char **argv, const char *args, char *retval);
int main(int argc, char *argv[])
{
int ch;
char retval[100];
while ((ch = cmdlineparse(argc, argv, ":bf:g", retval)) != -1) {
switch (ch) {
case 'b':
printf("b found. retval = %s\n",retval);
break;
case 'f':
printf("f found.\n");
break;
case 'g':
printf("g found. reval = %s\n",retval);
break;
default: /* or case 0: */
printf("bad argument!\n");
break;
}
}
getchar();
return 0;
}
/*
* function: cmdlineparse
* author: scrappy
* description: commandline parser
*
* int argc = number of commandline arguments
* const char **argv = 2d array of commandline arguments
* const char *args = options to check for. flag the option by
* placing a ':' before it and retval will be
* set to the commandline string following the
* option that was found. see example for
* clarification.
* char *retval = value set to argument following the option
* if the flag is set (with ':'). returns 0 if
* the argument does not exist.
*
* return values: 0 - option wasn't found (bad argument)
* -1 - function finished
* other - returns character found (non zero)
*/
int cmdlineparse(int argc, char **argv, const char *args, char *retval)
{
static int i = 1;
int j = 0;
int flag;
while( i < argc ) /* goes through each argument from commandline */
{
for( j = 0; j < strlen(args); j++ ) /* goes through each option */
{
flag = 0;
/* set flag to look for something after option/move onto next option */
if( args[j] == ':' ) {
flag = 1; j++;
}
/* checks for option, something can precede it if you want */
if( (argv[i][0] == args[j]) ^ (argv[i][1] == args[j]) ) {
if( flag == 1 ) {
if( i + 1 > argc - 1 ) { /* make sure next argument exists */
i++;
return 0;
}
strcpy( retval, argv[i+1] ); /* copy next argument into retval */
i++; /* additional increase to skip the next argument */
}
i++; /* move onto next argument */
return args[j];
}
} /* for( j = 0; j < strlen(args); j++ ) */
i++;
return 0; /* return 0 because option wasn't found in argument */
} /* for( ; i < argc; i++ ) */
return -1; /* end of function */
}
Suggestions, corrections, comments appreciated