简体   繁体   English

如何在主目录中创建文件夹?

[英]How to create a folder in the home directory?

I want to create a directory path = "$HOME/somedir" . 我想创建一个目录path = "$HOME/somedir"

I've tried using boost::filesystem::create_directory(path) , but it fails - apparently the function doesn't expand system variables. 我尝试过使用boost::filesystem::create_directory(path) ,但它失败了 - 显然该函数不会扩展系统变量。

How can I do it the simplest way? 我怎么能以最简单的方式做到这一点?

(note: in my case the string path is constant and I don't know for sure if it contains a variable) (注意:在我的情况下,字符串path是常量,我不确定它是否包含变量)

edit: I'm working on Linux (although I'm planning to port my app to Windows in the near future). 编辑:我正在Linux上工作(虽然我计划在不久的将来将我的应用程序移植到Windows)。

Use getenv to get environment variables, including HOME . 使用getenv获取环境变量,包括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. 您也可以使用系统shell和echo让shell为您执行此操作。

Getenv is portable (from standard C), but using the shell to do this portably will be harder between *nix and Windows. Getenv是可移植的(来自标准C),但是使用shell来移植它会在* nix和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. 环境变量约定也在* nix和Windows之间不同,但可能是字符串是可以针对给定平台修改的配置参数。

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: 如果您只需要支持扩展主目录而不是任意环境变量,则可以使用~ convention和~/somedir作为配置字符串:

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. 此行为是从Python的os.path.expanduser复制的,除了它只处理当前用户。 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. 通过检查目标平台而不是盲目地尝试不同的环境变量,可以改进与平台无关的尝试,即使不太可能在Linux上设置USERPROFILEHOMEDRIVEHOMEPATH

Off the top of my head, 在我的头顶,

namespace fs = boost::filesystem;
fs::create_directory(fs::path(getenv("HOME")));

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM