I'm trying to split a string into tokens to create an array of argument parameters. My current implementation is as follows (path
is the path to the user-executable file for which optional arguments are being read):
// ARG_MAX as defined in limits.h
int execute(char *exe) {
printf("args to %s: ", exe);
char *args = malloc(ARG_MAX);
scanf("%s", args);
char *argv[ARG_MAX];
int i = 0;
argv[i++] = exe;
while ((argv[i] = strsep(&args, " \t")) != NULL) {
i++;
}
free(args);
execv(exe, argv);
return 0;
}
What's confusing me is that from my understanding of strsep
this should be working as intended, and it does to an extent in that when tested it accurately allocates tokens[0]
to be path
, and tokens[1]
to be whatever tokens_s
up to the first whitespace character is.
When after a space you enter another argument, however, this is not allocated into tokens[2]
, and so on for subsequent arguments.
I can't seem to spot what it is I've done wrong when using strsep
that isn't leading to the desired functionality?
input:
exe = "/usr/bin/ps"
args = "-e -l"
output:
exec ps -e