I have two absolute filesystem paths (A and B), and I want to generate a third filesystem path that represents “A relative from B”.
Use case:
- Media player managing a playlist.
- User adds file to playlist.
- New file path added to playlist relative to playlist path.
- In the future, entire music directory (including playlist) moved elsewhere.
- All paths still valid because they are relative to the playlist.
boost::filesystem appears to have complete to resolve relative ~ relative => absolute, but nothing to do this in reverse (absolute ~ absolute => relative).
I want to do it with Boost paths.
As of version 1.60.0 boost.filesystem does support this. You’re looking for the member function
path lexically_relative(const path& p) const.Original, pre-1.60.0 answer below.
Boost doesn’t support this; it’s an open issue — #1976 (Inverse function for complete) — that nevertheless doesn’t seem to be getting much traction.
Here’s a vaguely naive workaround that seems to do the trick (not sure whether it can be improved):