int main(int argc, char **argv)
{
char input[150];
char change[2] = "cd";
char *directory;
while(1) {
prompt();
fgets(input, 150, stdin);
if(strncmp(change, input, 2) == 0) {
directory = strtok(input, " ");
directory = strtok(NULL, " ");
printf(directory);
chdir(directory);
perror(directory);
}
if(feof(stdin) != 0 || input == NULL) {
printf("Auf Bald!\n");
exit(3);
}
}
}
when i start this and type in “cd test” i get “no such file or directory”. But there is the directory “test”.
Runs on Arch Linux.
From the man page:
The problem is there’s a newline character
'\n'at the end of your string that you got fromfgets(), you need to remove it:Also:
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: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!