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?
Asked
Active
Viewed 5,180 times
12

Daniel
- 8,179
- 6
- 31
- 56
-
Have you tried to use http://www.boost.org/doc/libs/1_48_0/libs/filesystem/v3/doc/reference.html#canonical ? – Hamdor Oct 19 '15 at 22:23
-
@Hamdor I did try something like `canonical(path("~/test.txt"))`, but that didn't work. Incorrect usage? – Daniel Oct 19 '15 at 22:28
-
I doubt there is. But see also http://stackoverflow.com/questions/4891006/how-to-create-a-folder-in-the-home-directory – WhiteViking Oct 19 '15 at 23:13
1 Answers
7
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.
-
Note that this isn't cross-platform or guaranteed to work: https://stackoverflow.com/a/3733955/6296561 – Zoe May 01 '20 at 15:08
-
2This is actually downright wrong. For example, if you're logged in as user "admin", it will expand "~celmin/some/path" to "/home/admin/celmin/some/path" instead of the correct "/home/celmin/some/path". Even if you don't want to handle expanding another user's directory you should probably at least check that the second character is /. (Also as mentioned this only works on POSIX platforms.) – celticminstrel Feb 24 '21 at 15:13