Archive

Posts Tagged ‘getpwuid’

Get the HOME directory in C

October 23, 2013 No comments

In our programs, it’s usual to know where is the user home directory, to read/store configuration files, to search for something, or to know if the program is installed globally or locally.

There is a short function to get it:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
#include <stdlib.h>
#include <stdio.h>
#include <sys/types.h>
#include <pwd.h>

char *getHomeDir()
{
  static char *home = NULL;
 
  if (!home)
    {
      home = getenv("HOME") ;
    }
  if (!home)
    {
      struct passwd *pw = getpwuid(getuid());
      if (pw)
          home = pw->pw_dir ;
    }
  return home;
}

int main(int argc, char *argv[])
{
  printf ("HOME: %s\n", getHomeDir());

  return EXIT_SUCCESS;
}

If we look at getHomeDir() function, the directory we’re looking for is stored in a static variable, as we are not freeing this variable, we will get the value of this variable when we ask again (the user isn’t changing his home). We will ask the system just for the first time.

In the other hand, we have two ways of getting the PATH, the first is with the HOME environment variable, most of the times it will be defined and we can get it, but if it’s not there, we can get this information from /etc/passwd. There is much more information that what we want and we can have a look at the manual of getpwuid() to know what we can get (the user password is not included, muahaha, it isn’t stored there anymore, and if it is in an old or embedded system, you will probably see a hash).

Foto: Neetesh Gupta (Flickr) CC-by.

Top