I'm developing a cross-platform library that is meant to load configuration files from a user's home directory. The idea is to automatically provide configuration parameters without editing code.
This library can be used in desktop apps or in daemons/services. In (I assume) most Unix environments I can use getpwuid()
to get the home directory of the user. In Windows SO told me I could use SHGetKnownFolderPath but its documentation says its for desktop apps only. Is there a way to get this path, on Windows, for the user running a service?
For a console application the simplest method is to either retrieve the USERPROFILE
environment variable or concatenate the values of the HOMEDRIVE
and HOMEPATH
environment variables.
Use the getenv()
function in the standard library: https://msdn.microsoft.com/en-us/library/tehxacec.aspx
Example program:
#include <stdlib.h>
#include <stdio.h>
int main(int argc, char** argv) {
printf("USERPROFILE = %s\n", getenv("USERPROFILE"));
printf("HOMEDRIVE = %s\n", getenv("HOMEDRIVE"));
printf("HOMEPATH = %s\n", getenv("HOMEPATH"));
return 0;
}
Output:
USERPROFILE = C:\Users\myuser
HOMEDRIVE = C:
HOMEPATH = \Users\myuser