I am programming in C using VIM and terminal under Ubuntu Linux. In my program I
ID: 3879253 • Letter: I
Question
I am programming in C using VIM and terminal under Ubuntu Linux.
In my program I want to be able to change directories. When the user types CD and then a directory name, it should be able to switch to that directory. Here is what I have so far.
const char* NEWDIR = getenv(myArgv[1]);
int j = chdir(NEWDIR);
if (j < 0) {
printf("Can't change directory ");
}
else {
printf("Directory changed ");
printf("Newdir = %s ", NEWDIR);
}
For some reason it always says can't change directories. I think it may have something to do with my variable j but I can't figure it out. I would like you to rewrite my code for me. This is all in an if statement. It only gets to this point when the first word entered was CD.
Explanation / Answer
char *getenv(const char *name) searches for the environment name and returns the associated value to the string.
For example, getenv("PATH") would return something like "/sbin:/usr/sbin:/bin:/usr/bin:/usr/local/bin".
In you case, I think instead of calling getenv(myArgv[1]), you can directly pass the the value of myArgv[1] to the chdir function, something like below.
int j = chdir(myArgv[1]);
if(j == 0){
printf("Directory changed ");
printf("Newdir = %s ", (char *)myArgv[1]);
}
else{
switch(j){
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 ");
break;
default: perror("Couldn't change directory to %s", (char *) myArgv[1] );
}
}
Now, if the user enters something like CD "/usr/bin/", it should say
Directory changed
Newdir = /usr/bin/
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.