LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Programming (https://www.linuxquestions.org/questions/programming-9/)
-   -   Changing directory (https://www.linuxquestions.org/questions/programming-9/changing-directory-18269/)

pdstatha 04-11-2002 04:38 AM

Changing directory
 
Ok i've written some code which implements the cd command. Problem is it doesn't actually seem to change the directory at all. It says it has but when u do a pwd ur still in the same directory!!! WHY???????????????

Code:

/*The following code will implement the*
 *cd (change directory) command in UNIX.*/
#include <pwd.h>
#include <errno.h>
#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <unistd.h>

int main(int argc,char **argv){
  uid_t me;
  struct passwd *user;
  if(argc>1 && argv[1] != NULL){
    if((errno = chdir(argv[1])) == ENOTDIR){
      fprintf(stderr,"Can't change to %s\n",argv[1]);
      return -1;
    }else
          printf("Changed to %s\n",argv[1]);
  }else{
    me = getuid();
    user = getpwuid(me);
    if(!user){
      fprintf(stderr,"Couldn't find user %d\n",(int) me);
      exit(EXIT_FAILURE);
    }
    if((errno = chdir(user->pw_dir)) == ENOTDIR){
      fprintf(stderr,"Can't change to %s\n",user->pw_dir);
      return -1;
    }else
          printf("Changed to %s\n",user->pw_dir);
  }
  return EXIT_SUCCESS;
}


Mik 04-11-2002 07:08 AM

Well the program actually does change the directory but only for the environment in which the program is running. I hope you weren't expecting it to change the directory in the shell which you are running the program. It won't work that way.


All times are GMT -5. The time now is 05:03 PM.