First of all, your fgets
is reading to a single character buff
. You should read into a buffer of characters. Second, fgets
keeps the newline at the end of the read string, so you may want to remove it first, e.g.:
char buff[4096];
if (!fgets(buff, sizeof(buff), stdin)) {
// error or EOF
return 1;
}
int len = strlen(buff);
if (len > 0 && buff[len-1] == '\n') {
buff[--len] = '\0';
}
char *whtspc = strtok(buff, " ");
You must also replace all references to &buff
with buff
.
In addition to this, your malloc
is also wrong, and allocates one character less than is required (strlen
is without the terminating NUL):
if (!(comand[i] = malloc(strlen(whtspc)+1))) {
return 1; // out of memory
}
(void) strcpy(comand[i], whtspc);
Correspondingly your strncpy
was copying one character less than required. This is what made your original code accidentally work for a single-word input because it had the effect of removing the trailing '\n'
for you in that case, but in every other case it removed the last character of the word itself.
And the second argument to execvp
should be just the comand
(sic) array:
execvp(comand[0], comand);