I'm currently building my own shell. I managed to make ls function using scanf() and now I'm on cd. But I realized that cd has space between cd and file so I changed scanf() to fgets().
The space problem has been solved but another problem came out. Even though I typed correctly, the program won't work.
char command[MAX_LEN];
int result = 1;
char *pwd[MAX_LEN];
do {
printf("%s > ", getcwd(pwd, 100));
fgets(command, 100, stdin);
if(!strcmp("cd", command))
change_dir();
if(!strcmp("ls", command))
list_dir();
} while(strcmp("exit", command));
return 0;
What is wrong with my code? Can you please tell me why it's happening?
fgets reads up to size-1 chars (in your case 100-1 so 99) and places a '\0' at the end of the string, so when you type "ls" in stdin and hit enter, fgets will receive "ls\n" since enter creates a \n char, and the command will be "ls\n\0" since the \0 indicates the end of the string we can ignore this here for now.
When you strcmp("ls",command), you are comparing "ls" with the string in command that ends before \0 so "ls\n" since "ls" and "ls\n" are not the same, it will fail.
As others already have said, you could either add \n to your compare strings, or remove the \n since you may be planning to add more to the line after your cd or ls, you could look into string seperation e.g. with strtok()