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:
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!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With