This should work under Linux, Unix and OS X, for Windows you need to make a slight modification.
#include <stdlib.h>
#include <stdio.h>
#include <pwd.h>
#include <unistd.h>
int main(void)
{
const char *homeDir = getenv("HOME");
if (!homeDir) {
struct passwd* pwd = getpwuid(getuid());
if (pwd)
homeDir = pwd->pw_dir;
}
printf("Home directory is %s
", homeDir);
return 0;
}
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…