C - get home dir location in linux

20. February 2012 08:00

 

This is a short example of how to get the home directory location in linux in a C program. There is really a few choices here and depending on what your requirements are you might want to use one or other methods. The first method can be changed by the user. The second method cannot. However if the first method fails you should drop faill back on the other method.

 

The simple method is to pull the enviroment variable "HOME"

 

The slightly more complex method is to read it from the system user database.

 

 

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <pwd.h>
#include <sys/types.h>


int main(int argc, char **argv) {


        char *homedir = getenv("HOME");

        if (homedir != NULL) {
                printf("Home dir in enviroment");
                printf("%s\n", homedir);
        }

        uid_t uid = getuid();
        struct passwd *pw = getpwuid(uid);

        if (pw == NULL) {
                printf("Failed\n");
                exit(EXIT_FAILURE);
        }

        printf("%s\n", pw->pw_dir);

        return 0;
}

 

E-mail Kick it! DZone it! del.icio.us Permalink


Add comment




  Country flag
biuquote
  • Comment
  • Preview
Loading