Thread: why gentenv("PWD") doesn't work in home directory?

  1. #1
    Registered User
    Join Date
    Jul 2015
    Posts
    33

    why gentenv("PWD") doesn't work in home directory?

    I have this bit of code
    Code:
    } else if (strcmp(command->cmdArgs[0], "cd") == 0) {
                if (!command->cmdArgs[1]) {
                    // no directory was given
                    sprintf(dir, "%s", getenv("HOME"));
                } else if (strncmp(command->cmdArgs[1], "/", 1) == 0) {
                    sprintf(dir, "%s", command->cmdArgs[1]);
                } else {
                    // relative path
                    sprintf(dir, "%s/%s", getenv("PWD"), command->cmdArgs[1]);
                }
                
                if (chdir(dir) == -1) {
                    printf("no such file or directory\n");
                    fflush(stdout);
                    status = 1;
    //                exit(EXIT_FAILURE);
                }
    Let's say I'm in the current directory (e.g /some/test/dir) and I have these files/folders: test1.txt, testDir, and so on

    If I pass in "cd testDir" then I am able to cd into the testDir folder with chdir().

    But if I do "cd" first to go to HOME, then do mkdir testDir2, then do "cd testDir2" it doesn't work. Perror gives back no such file or directory
    I'm executing these commands with execvp().
    Last edited by jjwooyoung; 11-12-2016 at 07:14 PM.

  2. #2
    Registered User
    Join Date
    Jun 2015
    Posts
    1,640
    PWD does not magically keep track of your current directory. It's just an environment variable and needs to be updated each time you change directory if you want it's value to track your current directory.

    It will be properly set when you start your shell program (at least if you started it from another shell), but after that it's your job to update it if you want to. An alternative is to copy PWD's value into your own current_directory variable when your program starts up and then just keep current_directory up to date (and ignore PWD after that).
    Last edited by algorism; 11-12-2016 at 08:08 PM.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. FAQ-Draft: Why scanf("%c", &c) doesn't work as expected
    By AndiPersti in forum C Programming
    Replies: 19
    Last Post: 10-09-2012, 03:14 AM
  2. "strcpy(string,char[int])" doesn't work?
    By JonathanS in forum C Programming
    Replies: 4
    Last Post: 10-17-2011, 10:32 AM
  3. nbin=fopen("input.txt","a"); doesn't work?
    By Adam Rinkleff in forum C Programming
    Replies: 2
    Last Post: 06-23-2011, 02:57 PM
  4. "return function" doesn't work
    By Cris987 in forum C++ Programming
    Replies: 10
    Last Post: 03-04-2004, 11:04 PM
  5. Why doesn't "new line" work?
    By Moron Slayer in forum C++ Programming
    Replies: 14
    Last Post: 12-22-2003, 01:34 AM

Tags for this Thread