c++ 获取当前用户的根目录

来源:互联网 发布:wwe2k16优化 编辑:程序博客网 时间:2024/06/04 16:01

这个需求也是在最近开发的时候遇到的,起因是mkdir函数在创建文件夹的时候只能根据绝对路径创建,而这个绝对路径是不识别 ~  这样的符号的,也就是我们在linux下常用的基于~符号实现当前用户根目录定位无效,(注意   目前只发现这个函数不识别这个符号,而其他文件操作都是接受~标识符的)


在查找资料的时候发现 我们可以利用系统的环境变量来搞定这个需求,解决方案如下,我们在使用mkdir之前使用以下函数对路径进行转义

std::string expand_user(std::string path) {  if (not path.empty() and path[0] == '~') {    assert(path.size() == 1 or path[1] == '/');  // or other error handling    char const* home = getenv("HOME");    if (home or ((home = getenv("USERPROFILE"))) {      path.replace(0, 1, home);    }    else {      char const *hdrive = getenv("HOMEDRIVE"),        *hpath = getenv("HOMEPATH");      assert(hdrive);  // or other error handling      assert(hpath);      path.replace(0, 1, std::string(hdrive) + hpath);    }  }  return path;}


解决方案来自于 http://stackoverflow.com/questions/4891006/how-to-create-a-folder-in-the-home-directory


原文


Use getenv to get environment variables, including HOME. If you don't know for sure if they might be present, you'll have to parse the string looking for them.

You could also use the system shell and echo to let the shell do this for you.

Getenv is portable (from standard C), but using the shell to do this portably will be harder between *nix and Windows. Convention for environment variables differs between *nix and Windows too, but presumably the string is a configuration parameter that can be modified for the given platform.

If you only need to support expanding home directories rather than arbitrary environment variables, you can use the "~" convention and then "~/somedir" for your configuration strings:

std::string expand_user(std::string path) {  if (not path.empty() and path[0] == '~') {    assert(path.size() == 1 or path[1] == '/');  // or other error handling    char const* home = getenv("HOME");    if (home or ((home = getenv("USERPROFILE"))) {      path.replace(0, 1, home);    }    else {      char const *hdrive = getenv("HOMEDRIVE"),        *hpath = getenv("HOMEPATH");      assert(hdrive);  // or other error handling      assert(hpath);      path.replace(0, 1, std::string(hdrive) + hpath);    }  }  return path;}

This behavior is copied from Python's os.path.expanduser, except it only handles the current user. The attempt at being platform agnostic could be improved by checking the target platform rather than blindly trying different environment variables, even though USERPROFILE, HOMEDRIVE, and HOMEPATH are unlikely to be set on Linux.

shareimprove this answer

0 0