如何创建主目​​录文件夹? [英] How to create a folder in the home directory?

查看:232
本文介绍了如何创建主目​​录文件夹?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想创建一个目录 PATH =$ HOME / somedir

我已经使用的boost ::文件系统:: create_directory(路径),但它失败尝试。

I've tried using boost::filesystem::create_directory(path), but it fails - apparently the function doesn't expand system variables.

我怎么能做到这一点最简单的方法?

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)

编辑:我的工作在Linux上(虽然我打算端口我的应用程序到Windows在不久的将来)

edit: I'm working on Linux (although I'm planning to port my app to Windows in the near future).

推荐答案

使用 GETENV 获得环境变量,包括HOME。如果你不知道是否他们可能会被present做,你必须解析字符串寻找。

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.

您还可以使用系统shell和呼应,让外壳为你做这个。

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

GETENV是可移植的(从标准C),但使用shell来可移植这样做将更为困难的* nix和Windows之间。公约的环境变量的* nix和Windows之间的区别了,但是presumably的字符串是一个配置参数可以为特定平台进行修改。

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.

如果你只需要支持扩大主目录,而不是随意的环境变量,你可以用〜约定,然后〜/ somedir为您配置字符串:

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

此行​​为是从Python的 os.path.expanduser 复制除了它只能处理当前用户。在成为平台无关的尝试可以通过检查目标平台,而不是盲目地尝试不同的环境变量,即使USERPROFILE,HOMEDRIVE和HOMEPATH不太可能在Linux上设置有待提高。

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.

这篇关于如何创建主目​​录文件夹?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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