1820620 Members
1949 Online
109626 Solutions
New Discussion юеВ

How to get the PWD

 
SOLVED
Go to solution
Satya_6
Frequent Advisor

How to get the PWD

Hi,

how do I get the working directory in my c code?

I used `getenv` to get the current work directory, but it is returning NULL.

TIA
satya
3 REPLIES 3
Bruno Vidal
Respected Contributor

Re: How to get the PWD

Hi,
For myself, it works perfectly:

#include
main()
{
printf("%s\n",getenv("PWD"));
}


#cc -o toto toto.c
#./toto
/tmp

What's your code that return NULL ?
A. Clay Stephenson
Acclaimed Contributor
Solution

Re: How to get the PWD

The cleaner way to do this from C is to simply use the getcwd() function. Man 3 getcwd for details.
If it ain't broke, I can fix that.
Mike Stroyan
Honored Contributor

Re: How to get the PWD

getcwd() and getenv("PWD") may disagree if you cd through a symbolic link. The shell tracks current working directory with the symbolic link name in PWD. The getcwd() function uses a series of ".." steps with readdir and lstat to find the real directory names on the way to up to "/".

% echo $PWD
/home/stroyan
% mkdir real
% ln -s real symbolic
% cd symbolic
% echo $PWD
/home/stroyan/symbolic
% pwd
/home/stroyan/symbolic
% /usr/bin/pwd
/home/stroyan/real