Chdir () - no such file or directory

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 run this and type โ€œcd testโ€, I get โ€œno such file or directoryโ€. But there is a "test" directory.

Works in Arch Linux.

+6
source share
1 answer

On the man page:

fgets () reads no more than one character of size from the stream and stores them in the buffer pointed to by s. Reading stops after EOF or a new line. If a new line is read, it is saved in the buffer.

The problem is the newline character '\n' at the end of the line you received from fgets() , you need to remove it:

 fgets(input, 150, stdin); input[strlen(input)-1] = '\0'; 

also:

 char change[2] = "cd"; 

This should be change[3] , this is 2 (for "cd") + 1 for the NULL terminator '\0' , which is automatically placed for you.

Then it should work.

EDIT

Another alternative is to change the call to strtok() so that:

 directory = strtok(NULL, " \n"); 

This will work if the user enters a string using the enter key or using the EOF character (ctrl + d on Linux) ... I'm not sure how likely the second is for the user ... but that could not hurt!

+4
source

All Articles