C++ 使用boost::filesystem扩展用户路径

C++ 使用boost::filesystem扩展用户路径,c++,boost-filesystem,C++,Boost Filesystem,boost::filesystem中是否有类似于Python中提供的功能来扩展以用户主目录符号(~在Unix上)开头的路径?否。 但您可以通过执行以下操作来实现: namespace bfs = boost::filesystem; using std; bfs::path expand (bfs::path in) { if (in.size () < 1) return in; const char * home = getenv ("HOME");

boost::filesystem
中是否有类似于Python中提供的功能来扩展以用户主目录符号(
~
在Unix上)开头的路径?

否。

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

  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;
    }
  }
namespace bfs=boost::filesystem;
使用性病;
bfs::路径扩展(bfs::路径中){
如果(in.size()<1)返回;
const char*home=getenv(“home”);
if(home==NULL){

cerr你试过使用吗?@Hamdor我试过类似于
canonical(path(“~/test.txt”)
,但不起作用。不正确的用法?我怀疑有。但请注意,这不是跨平台的,也不能保证有效:这实际上是完全错误的。例如,如果你以用户“admin”登录,它将扩展“~celmin/some/path”改为“/home/admin/celmin/some/path”,而不是正确的“/home/celmin/some/path”。即使您不想处理扩展另一个用户的目录,您可能至少应该检查第二个字符是否为/(如前所述,这仅适用于POSIX平台)