Reputation: 107
I was trying to split the array I received as an argument in a function using strtok()
and it simply don't work as expected.
For example I receive this string : "ls -l"
and I got only "ls"
.
Furthermore , I want to store the tokens into an array of strings.
Here is what I have done so far:
int mysystem(char *s) {
int i;
char *tok , *aux;
int conta = 0;
int pid, status;
int j = 0;
tok = strtok(s , " ");
while (tok != NULL) {
tok = strtok(NULL, s);
conta++;
}
char *store[conta];
i = 0;
aux = strtok(s ," ");
while (aux != NULL) {
store[i] = aux;
aux = strtok(NULL, s);
i++;
}
pid = fork();
if (pid == 0)
execvp(store[0], store);
while (j != conta) {
wait (&status);
j++;
}
return 0;
}
This is the main of where I'm passing the string to my function :
int main(int args, char **arg) {
int i;
int s;
int f = 0;
if (args >= 2) {
int length = 0;
for (i = 1; i < args; ++i) {
length += strlen(arg[i]);
}
char *output = (char*)malloc(length + 1);
char *dest = output;
i = 1;
while (i < args) {
dest = strcat (dest,arg[i]);
i++;
if (i < args) {
dest = strcat (dest," ");
}
}
dest = strcat(dest, "\0");
s = mysystem(dest);
free(output);
return s;
}
}
Upvotes: 0
Views: 182
Reputation: 13189
strtok
modifies the string, so you can't run it twice on the same string. s
has been converted to a series of strings separated by NUL
characters. Change to using an array which is "long enough" and just go through s once.
Upvotes: 1