Groovy hepcat Jeff Rodriguez was jivin' on Fri, 12 Dec 2003 20:36:37
-0700 in comp.lang.c.
Parsing options in the same way they are passed to main's a cool
scene! Dig it!
If main is prototyped as:
int main(int argc, char *argv[]);
You will end up with a bunch of arguments in *argv, and the number in argc. Now
what I want to do is emulate that same action on a string. Say for example I have:
char *command = "./blah --arg1 --arg2 123 -x --arg2=w00t"
How do I acheive the same effect as in main()?
First of all, don't try to do this with a string literal; use an
array.
Use strtok() to get each token in turn, and add each (pointer
returned from strtok()) to an array of pointers to char which has been
dynamically allocated with realloc(), until (and including) strtok()
returns a null pointer. For example:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
char **gettoks(char *s, int *num)
{
char **tok = NULL, **tmp;
char *t;
int n = 0;
t = strtok(s, " \t\v\r\n");
while(t)
{
n++;
tmp = realloc(tok, n * sizeof *tmp);
if(!tmp)
{
free(tok);
return NULL;
}
tok = tmp;
tok[n - 1] = t;
t = strtok(NULL, " \t\v\r\n");
}
tmp = realloc(tok, (n + 1) * sizeof *tmp);
if(!tmp)
{
free(tok);
return NULL;
}
tok = tmp;
tok[n] = NULL;
*num = n;
return tok;
}
int main(void)
{
char command[] = "./blah --arg1 --arg2 123 -x --arg2=w00t";
char **argv;
int argc, i;
argv = gettoks(command, &argc);
if(!argv)
{
fprintf(stderr, "Memory allocation error.\n");
return EXIT_FAILURE;
}
printf("%d args found:\n", argc);
for(i = 0; i < argc; i++)
{
printf("\t%d: \"%s\"\n", i, argv
);
}
free(argv);
return 0;
}
--
Dig the even newer still, yet more improved, sig!
http://alphalink.com.au/~phaywood/
"Ain't I'm a dog?" - Ronny Self, Ain't I'm a Dog, written by G. Sherry & W. Walker.
I know it's not "technically correct" English; but since when was rock & roll "technically correct"?