Hello everyone.
I'm trying to code the cd shell command in c. I used chdir function to code it but the problem is that when I execute the program on the terminal it doesn't change the directory. I kept a series printfs and conditions to test if it changes, though it does change, I don't see it on the terminal. Here's my code:
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <errno.h>
int main( int argc, char **argv[] ) {
int result = 0;
if (argc > 2) {
printf("%s: Too many operands \nUsage: %s <pathname>\n", (char *) argv[0], (char *) argv[0]);
exit(1);
}
if(argc == 1) {
printf("argc is 1\n");
const char* home = getenv("HOME");
int i = chdir(home);
if(i < 0)
printf("directory couldn't be changed\n");
else{
printf("directory changed\n");
printf("home = %s\n", home);
}
exit(0);
}
result = chdir(argv[1]);
if(result == 0){
printf("directory changed\n");
exit(0);
}
else{
switch(result){
case EACCES: perror("Permission denied");
break;
case EIO: perror("An input output error occured");
break;
case ENAMETOOLONG: perror("Path is to long");
break;
case ENOTDIR: perror("A component of path not a directory");
break;
case ENOENT: perror("No such file or directory"); printf("enoent\n");
default: perror("Couldn't change directory to %s", (char *) argv[1] );
}
}
return 0;
}
Any ideas? Thanks