Here you should check first if space is
NULL
(when the command does not contain a space or new line character):
char * space = strtok(cmdline," \n");
Otherwise your program will crash.
This will write a
NULL
char behind the string (behind the existing
NULL
char):
space[strlen(space)+1]='\0';
I guess you want to remove a trailing line feed here. Because that would let the system
chdir
command fail. So it should be something like this:
while (*space == ' ')
space++;
int len = strlen(space);
if (space[len-1] == '\n')
space[len-1] = '\0';
However, a better implementation would check for multiple line feeds and also carriage returns.
Just use an existing command to see what happens:
cmdline = "cwd directory\n"
Then space would point to " directory\n". Passing that to
chdir
will off course fail. So skip the leading space(s) and remove the trailing line feed to get "directory".