Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Expanding user path with boost::filesystem

Is there functionality in boost::filesystem to expand paths that begin with a user home directory symbol (~ on Unix), similar to the os.path.expanduser function provided in Python?

like image 976
Daniel Avatar asked Oct 19 '15 22:10

Daniel


1 Answers

No.

But you can implement it by doing something like this:

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

Also, have a look at the similar question suggested by @WhiteViking.

like image 133
gauteh Avatar answered Oct 17 '22 18:10

gauteh