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?
Starting with Windows Vista, the Windows home directory is \user\username. In prior Windows versions, it was \Documents and Settings\username. In the Mac, the home directory is /users/username, and in most Linux/Unix systems, it is /home/username.
To navigate to your home directory, use "cd" or "cd ~" To navigate up one directory level, use "cd .." To navigate to the previous directory (or back), use "cd -"
The equivalent of Ubuntu's ~/ (a.k.a. /home/yourusername/ ) in Windows 10 is C:\Users\yourusername\ .
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With