Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get user home directory on Windows?

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?

like image 413
ruipacheco Avatar asked Mar 09 '17 13:03

ruipacheco


People also ask

How do I find the home directory of a user in Windows?

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.

How do I get to my home directory in CMD?

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 -"

What is the home directory in Windows 10?

The equivalent of Ubuntu's ~/ (a.k.a. /home/yourusername/ ) in Windows 10 is C:\Users\yourusername\ .


1 Answers

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
like image 150
Paul Avatar answered Nov 13 '22 12:11

Paul