From the man page:
fgets() reads in at most one less than size characters from stream and stores them into the buffer pointed to by s. Reading stops after an EOF or a newline. If a newline is read, it is stored into the buffer.
The problem is there's a newline character '\n'
at the end of your string that you got from fgets()
, you need to remove it:
fgets(input, 150, stdin);
input[strlen(input)-1] = '\0';
Also:
char change[2] = "cd";
That should be change[3]
, it's 2 (for "cd") + 1 for the NULL terminator '\0'
which is automatically placed for you.
Then it should work.
EDIT:
A different alternative is to change the strtok()
call such that:
directory = strtok(NULL, " \n");
This will work if the user enters the string via the enter key or via the EOF (ctrl + d on Linux) character... I'm not sure how likely the second is for a user to do... but it couldn't hurt!