Google Groups no longer supports new Usenet posts or subscriptions. Historical content remains viewable.
Dismiss

Newbie Question: How to retrieve homedir in c++?

0 views
Skip to first unread message

Markus Wolters

unread,
Apr 2, 2003, 4:44:10 PM4/2/03
to
I need to find the homedir of the active user in c++. Could anyone help me?

Thanks Markus


Andrew Taylor

unread,
Apr 2, 2003, 4:58:30 PM4/2/03
to
Markus Wolters wrote:

> I need to find the homedir of the active user in c++. Could anyone help me?
>
> Thanks Markus
>

Recommended way:
char *homedir = getenv("HOME");

Another way:
char *homedir = getpwuid(getuid())->pw_dir;

The latter is discouraged because the user cannot override it at
runtime. Even worse is reading /etc/passwd directly, which may fail if
NIS is being used.

--
Andrew

Kasper Dupont

unread,
Apr 3, 2003, 2:09:06 AM4/3/03
to
Markus Wolters wrote:
>
> I need to find the homedir of the active user in c++. Could anyone help me?

http://www.daimi.au.dk/~kasperd/comp.os.linux.development.faq.html#homedir

--
Kasper Dupont -- der bruger for meget tid på usenet.
For sending spam use mailto:aaa...@daimi.au.dk
for(_=52;_;(_%5)||(_/=5),(_%5)&&(_-=2))putchar(_);

Josef Möllers

unread,
Apr 3, 2003, 2:29:59 AM4/3/03
to

It depends on whether Markus would allow his users to specify what is
considered the "home directory" or if he is interested in "the real home
directory" or. Sometimes the former ("cheating") might be desireable,
sometimes it isn't.

Josef
--
Josef Möllers (Pinguinpfleger bei FSC)
If failure had no penalty success would not be a prize
-- T. Pratchett

Kasper Dupont

unread,
Apr 3, 2003, 3:22:09 AM4/3/03
to
Josef Möllers wrote:
>
> It depends on whether Markus would allow his users to specify what is
> considered the "home directory" or if he is interested in "the real home
> directory" or. Sometimes the former ("cheating") might be desireable,
> sometimes it isn't.

Yes, if it is a suid executable you probably shouldn't be able to
specify an alternate home. But otherwise you should be able to.

Roger Leigh

unread,
Apr 3, 2003, 2:04:05 PM4/3/03
to
"Markus Wolters" <markus...@gmx.de> writes:

> I need to find the homedir of the active user in c++. Could anyone help me?

In order of preference:

const char *homedir = getenv("HOME"); /* Get from environment */

uid_t id = getuid();
struct passwd *pass = getpwuid(id);
const char *homedir = pass->pw_dir; /* Get from user database */

After these two checks, you must stat(2) homedir and make sure a) it
exists and b) is a directory.

const char *homedir = "/"; /* Last resort if all else fails */


Obviously, you'll do proper error checking of each function call in
your own program. If the program needs to be secure, you might
disallow getting $HOME from the envirionment, since you won't want it
to be overridable.


HTH,
Roger

--
Roger Leigh

Printing on GNU/Linux? http://gimp-print.sourceforge.net/
GPG Public Key: 0x25BFB848 available on public keyservers

0 new messages