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.