I prefer to seperate the handling of the command-line options from the main program. As an example, I created a program that took a bitmap picture, and sliced it up into tiles (of any size), then saved the resulting tile-map to a new bitmap file, while having the option to create a .map and to go into verbose-mode.
So I created an OPTION structure to hold all the command-line options / switches first:
Code:
typedef struct Options
{
char *source, // source filename
*tiles, // tile bmp filename
*map; // map filename
int x, // tiles width
y; // tiles height
BOOL v; // verbose (on/off)
} OPTIONS;
Then, I created the function that scans the command-line and fills in the OPTION structure:
Code:
void OPT_Parse (int argc, char *argv[], OPTIONS *opt)
{
int i = 2;
/* Clear the opt structure
before we fill it in. */
memset (opt, 0, sizeof (OPTIONS));
/* See if there even are
any arguments given. */
if (argc > 1)
{
/* The first argument is
always the source file. */
opt->source = argv[1];
while (++ i <= argc)
{
/* Argument -c creates a tile BMP. */
if (! (strncmp (argv[i - 1], "-c", 2)))
opt->tiles = argv[i ++];
/* Argument -m creates a map file. */
else if (! (strncmp (argv[i - 1], "-m", 2)))
opt->map = argv[i ++];
/* Argument -x sets the tile width. */
else if (! (strncmp (argv[i - 1], "-x", 2)))
opt->x = atoi (argv[i ++]);
/* Argument -y sets the tile height. */
else if (! (strncmp (argv[i - 1], "-y", 2)))
opt->y = atoi (argv[i ++]);
/* Turn on verbose mode. */
else if (! (strncmp (argv[i - 1], "-v", 2)))
opt->v = TRUE;
}
/* If no tile width- or height was
specified, we use the default values. */
if (! opt->x)
opt->x = 8;
if (! opt->y)
opt->y = 8;
}
}
This has an added bonus that the order of the commands and/or switches do not matter, the only thing it expects is that the first argument is the source filename, which is why I declared the index variable i as 2, as argv[2] is the first place an option should exist.
Then the main code can check the OPTIONS structure and do things accordingly.
Hope this helps a bit.