Search code examples
c++unixdirectorychdir

chdir(<directory>) doesn't change directory: No such file or directory


I want to create a simple c++ programm, that changes directory.

int main(int argc, char * argv[]){
//...
char input[256];
char *command;

//read command
fgets(input, 256, stdin);

// CODE ADDED WITH HELP
command = strchr(input, '\n');
    
if(command){
    *command = '\0';
}
// CODE ADDED WITH HELP

if(strncmp(input, "cd ",3)==0){
    strtok(input, " ");
    command = strtok(NULL, "\0");
    if(chdir(command) != 0){
        perror("Error while changing directory. Please try again!");
    }
}
//...
}

In the programm above you can see the code between the comment "CODE ADDED WITH HELP". This was added after. The programm works now but I am trying to understand why it works now and why it didn't before.

If you think the piece of code added away I was getting the error "No such file or directory" while trying to change directory. After I got some help and added a couple lines of code I can now successfully change directories.

I am trying to understand what the piece of code exactly does in the context of what I am trying to achieve and why it doesn't work without it.


Solution

  • fgets(input, 256, stdin);
    

    This reads a single line of text, including the trailing newline character. The Enter key generates the "newline" character, which is part of the input.

    chdir(command);
    

    Unless additional measures are taken, the trailing newline character remains in command.

    The Golden Rule Of Computer Programming reads: "your computer will always do exactly what you tell it to do instead of what you want it to do". So, let's say you have a subdirectory named "book", and you typed in "book", as the input to your program.

    For the reasons explained above, command's contents would be "book\n", and an attempt will be made to change the current directory to a directory whose name is "book\n", that is "book" followed by a newline character. This would be what you will be telling your computer to do. Since there is no such directory, your computer will fail to follow your request.

    The added code simply finds the trailing newline character, which will always be the last character entered and replaces it with a '\0'. The shown code uses C-style strings, which are terminated by the '\0' character (the original read input ends with the newline character, and fgets helpfully adds the original '\0' character after that, which can rest in peace). The End.