When I use chdir() to change the current working directory, why doesn’t the getenv(“PWD”) give the present working directory? Do I need to setenv(“PWD”,newDir,1) also?
void intChangeDir(char *newDir)
{
if( chdir(newDir)==0 )
{
printf("Directory changed. The present working directory is \"%s\" \"%s\"\n",getenv("PWD"),getcwd(NULL,0));
}
else
{
printf("Error changing dir %s\n",strerror(errno));
}
}
Output: (location of the executable is /home/user)
changedir /boot
Directory changed. The present working directory is “/home/user” “/boot”
Yes, if you want to change the environment variable, you have to explicitly do that.
It’s shell that sets and updates
PWDin the normal run of events, so it only reflects changes of the current directory known to the shell.