【问题标题】:Expanding user path with boost::filesystem使用 boost::filesystem 扩展用户路径
【发布时间】:2016-01-18 10:06:47
【问题描述】:

boost::filesystem 中是否具有扩展以用户主目录符号(Unix 上为 ~)开头的路径的功能,类似于 Python 中提供的 os.path.expanduser 函数?

【问题讨论】:

标签: c++ boost-filesystem


【解决方案1】:

没有。

但是您可以通过执行以下操作来实现它:

  namespace bfs = boost::filesystem;
  using std;

  bfs::path expand (bfs::path in) {
    if (in.size () < 1) return in;

    const char * home = getenv ("HOME");
    if (home == NULL) {
      cerr << "error: HOME variable not set." << endl;
      throw std::invalid_argument ("error: HOME environment variable not set.");
    }

    string s = in.c_str ();
    if (s[0] == '~') {
      s = string(home) + s.substr (1, s.size () - 1);
      return bfs::path (s);
    } else {
      return in;
    }
  }

另外,看看@WhiteViking 建议的similar question

【讨论】:

  • 请注意,这不是跨平台或保证工作:stackoverflow.com/a/3733955/6296561
  • 这实际上是完全错误的。例如,如果您以用户“admin”身份登录,它会将“~celmin/some/path”扩展为“/home/admin/celmin/some/path”,而不是正确的“/home/celmin/some /小路”。即使您不想处理扩展另一个用户的目录,您至少应该检查第二个字符是否为 /。 (也如前所述,这只适用于 POSIX 平台。)
猜你喜欢
  • 2011-02-15
  • 2012-09-20
  • 2010-09-28
  • 2010-12-17
  • 2012-04-27
  • 1970-01-01
  • 1970-01-01
  • 2011-04-25
相关资源
最近更新 更多