Archived

This topic is now archived and is closed to further replies.

Feral

c function to find home directory? or $HOME?

Recommended Posts

I tried to google but had less than zero luck, well ok SHGetFolderpath ... though that same link hinted at $HOME as how to find home... Anyway I am trying to find the user''s home directory... is there a C function for this? Or, do I have to get it from the HOME env var? (and can I rely on $HOME being available all the time/place?) Thank you kindly

Share this post


Link to post
Share on other sites
Guest Anonymous Poster
quote:
Original post by FeralofFireTop

I tried to google but had less than zero luck, well ok SHGetFolderpath ... though that same link hinted at $HOME as how to find home...

Anyway I am trying to find the user''s home directory... is there a C function for this? Or, do I have to get it from the HOME env var? (and can I rely on $HOME being available all the time/place?)


Thank you kindly





I assume u mean on a unix box since u posted this here. on linux/glibc (i''m not sure if this is posix compatible), use getpwent(). Do not rely on $HOME, esp if your program is going to be run suid/sgid.

Share this post


Link to post
Share on other sites
*nod* *nod* Yup yup was mindfull of what forum I was posting in

Thank you for the help

What I came up with...



// *nix things to find user''s home dir.

#include <unistd.h> // getuid

#include <pwd.h> // getpwent() and struct passwd


void main(void)
{
char caBuffer[1024]; // I technically am using a std::string

// uid_t should be a uint32

uid_t MyUID = getuid();
passwd * pPW = NULL;

while( (pPW = getpwent() ) != NULL)
{
if ( pPW->pw_uid == MyUID)
{
break; // Break out of closest do, for, while

}
}
if ( pPW != NULL)
{
strcpy(caBuffer, pPW->pw_dir);
}
endpwent(); // close


printf("!! %s\n", caBuffer); // "!! /home/feral"

}

//END



An I liked the simplicity of ''printf("!! %s\n", getenv("HOME") );'' too!

Share this post


Link to post
Share on other sites
Guest Anonymous Poster
quote:
Original post by FeralofFireTop

while( (pPW = getpwent() ) != NULL)
{
if ( pPW->pw_uid == MyUID)
{
break; // Break out of closest do, for, while

}
}



All that can be replaced with "pPW=getpwuid(getuid());"

Share this post


Link to post
Share on other sites
Ahh! wonderful, thank you for pointing that out!

... now that (code) is the efficient and simplicity I was expecting to find (in *nix land), heh.

Anyway thank you again

Share this post


Link to post
Share on other sites