LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Programming (https://www.linuxquestions.org/questions/programming-9/)
-   -   How to get home directory of a login user (https://www.linuxquestions.org/questions/programming-9/how-to-get-home-directory-of-a-login-user-417330/)

lucky6969b 02-19-2006 08:15 PM

How to get home directory of a login user
 
From Fedora 4, how do you get the home dir of a login user. (C/C++ Programming) Say I login as john I get
/home/John
If I login as Kim I get
/home/Kim
Couldn't find it on Google
Thanks
Jack

paulsm4 02-19-2006 08:29 PM

1. If you want the home for the user running the program:
Code:

char *s = getenv ("HOME");
2. If you want the home for any arbitrary user, then you'll need to "grep" /etc/passwd:
EXAMPLE:
Code:

  char cmd[256], homedir[256];
  sprintf (cmd, "grep %s /etc/passwd|awk -F : '{print $6}'", username);
  FILE *fp = popen (cmd, "r");
  if (fp)
  {
    fgets (homedir, sizeof homedir, fp);
    pclose (fp);
  }


lucky6969b 02-19-2006 08:32 PM

Great Info!
Thanks Paul
I need to get various info. from the SBC too. Are there some good books that you would recommend?
Jack

paulsm4 02-19-2006 11:22 PM

Hi -

By "SBC", I assume you mean "Single Board Computer", as in "Embedded System". Correct?

I don't know - you're probably more conversant with the options than I am at this point.

Off the top of my head, "/proc" has a lot of great info - if your SBC's Linux kernel is new enough to support the /proc virtual filesystem:

http://www.comptechdoc.org/os/linux/...ux_hlproc.html
http://www.redhat.com/docs/manuals/l...e/ch-proc.html
<= I'd also suggest looking at /proc for your other question, about memory cache

Although I think I might have already recommended them, a couple of books that might be of use to you include:

Building Embedded Linux Systems, Karim Yaghmour
http://www.bookpool.com/sm/059600222X

Linux Kernel Development, 2nd Ed, Robert Love
http://www.bookpool.com/ss?qs=linux+...t+love&x=0&y=0

'Hope that helps .. PSM

jlliagre 02-20-2006 01:34 AM

Quote:

Originally Posted by paulsm4
2. If you want the home for any arbitrary user, then you'll need to "grep" /etc/passwd:
EXAMPLE:
Code:

  char cmd[256], homedir[256];
  sprintf (cmd, "grep %s /etc/passwd|awk -F : '{print $6}'", username);
  FILE *fp = popen (cmd, "r");
  if (fp)
  {
    fgets (homedir, sizeof homedir, fp);
    pclose (fp);
  }


A simpler, better and more secure approach would be to use getpwnam.
Code:

#include <pwd.h>

...
        struct passwd *p;
        p=getpwnam(username);
        printf("%s\n", p->pw_dir);
...


lucky6969b 02-20-2006 01:46 AM

Hi Paul,
Yes. I am working on an application for the Single Board Computer. I need to obtain info like platform that the user is using, cache memory available and other configuration info. I'm now working hard to figure out the rest...
Thanks a lot
Jack


All times are GMT -5. The time now is 10:43 AM.