Back to index

radiance  4R0+20100331
gethomedir.c
Go to the documentation of this file.
00001 #ifndef lint
00002 static const char RCSid[] = "$Id: gethomedir.c,v 1.1 2003/10/27 10:20:58 schorsch Exp $";
00003 #endif
00004 /*
00005  *  gethomedir.c - search for a users home directory
00006  *
00007  */
00008 
00009 #include  "copyright.h"
00010 
00011 #include <stdlib.h>
00012 #include <string.h>
00013 
00014 #include "rtio.h"
00015 
00016 #ifdef _WIN32
00017 
00018 char *
00019 gethomedir(char *uname, char *path, int plen)
00020 {
00021        char *cd, *cp;
00022 
00023        if (uname == NULL || *uname == '\0') {    /* ours */
00024               /* pretend we're on unix first (eg. for Cygwin) */
00025               if ((cp = getenv("HOME")) != NULL) {
00026                      strncpy(path, cp, plen);
00027                      path[plen-1] = '\0';
00028                      return path;
00029               }
00030               /* now let's see what Windows thinks */
00031               if ((cd = getenv("HOMEDRIVE")) != NULL
00032                             && (cp = getenv("HOMEPATH")) != NULL) {
00033                      strncpy(path, cd, plen);
00034                      strncat(path, cp, plen-2);
00035                      path[plen-1] = '\0';
00036                      return path;
00037               }
00038               return NULL;
00039        }
00040        /* No idea how to find the home directory of another user */
00041        return NULL;
00042 }
00043        
00044 #else /* _WIN32 */
00045 
00046 
00047 #include <unistd.h>
00048 #include <pwd.h>
00049 #include <sys/types.h>
00050 
00051 char *
00052 gethomedir(char *uname, char *path, int plen)
00053 {
00054        struct passwd *pwent;
00055        uid_t uid;
00056        char *cp;
00057 
00058        if (uname == NULL || *uname == '\0') {    /* ours */
00059               if ((cp = getenv("HOME")) != NULL) {
00060                      strncpy(path, cp, plen);
00061                      path[plen-1] = '\0';
00062                      return path;
00063               }
00064               uid = getuid();
00065               if ((pwent = getpwuid(uid)) == NULL)
00066                      return(NULL); /* we don't exist ?!? */
00067               strncpy(path, pwent->pw_dir, plen);
00068               path[plen-1] = '\0';
00069               return path;
00070        }
00071        /* someone else */
00072        if ((pwent = getpwnam(uname)) == NULL)
00073               return(NULL); /* no such user */
00074 
00075        strncpy(path, pwent->pw_dir, plen);
00076        path[plen-1] = '\0';
00077        return path;
00078 }
00079 
00080 #endif /* _WIN32 */
00081