如何在Windows上获取用户主目录? [英] How to get user home directory on Windows?

查看:307
本文介绍了如何在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.

此库可在桌面应用程序或守护程序/服务中使用.在(我假设)大多数Unix环境中,我可以使用getpwuid()来获取用户的主目录.在Windows SO 告诉我中,我可以使用

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?

推荐答案

对于控制台应用程序,最简单的方法是检索USERPROFILE环境变量或连接HOMEDRIVEHOMEPATH环境变量的值.

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.

使用标准库中的getenv()函数: https://msdn.microsoft.com/en-us/library/tehxacec.aspx

Use the getenv() function in the standard library: https://msdn.microsoft.com/en-us/library/tehxacec.aspx

示例程序:

#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;
}

输出:

USERPROFILE = C:\Users\myuser
HOMEDRIVE   = C:
HOMEPATH    = \Users\myuser

这篇关于如何在Windows上获取用户主目录?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆