Here's how I do it in the library that I create on top of the boost file system:
Step 1: Define the "deepest common root." In principle, this is the most common common denominator for the two paths. For example, if you have 2 paths: "C: \ a \ b \ c \ d" and "C: \ a \ b \ c \ l.txt", then the common root they share is "C: \ a \ B \ s \ ".
To get this, convert both paths to the canonical form of absolute NOT (you'll want to do this for speculative paths and symbolic links).
Step 2: To go from A to B, you suffix A with enough copies of "../" to move the directory tree to a common root, then add the line for B to go down the tree to it. In windows, you can have 2 paths without a common root, so the transition from any A to any B is not always possible.
namespace fs = boost::filesystem; bool GetCommonRoot(const fs::path& path1, const fs::path& path2, fs::path& routeFrom1To2, std::vector<fs::path>& commonDirsInOrder) { fs::path pathA( fs::absolute( path1)); fs::path pathB( fs::absolute( path2));
}
This will do what you want - you go up from A until you click on the shared folder, and B both descendants, and then go to B. You probably don't need the return of "commonDirsInOrder", which there is me, but the return of "routeFrom1To2" is the one you are requesting.
If you plan to actually change the working directory to "B", you can directly use "routeFrom1To2". Keep in mind that this function will create an absolute path, despite all the parts "..", but this should not be a problem.
Zack Yezek Jan 14 '14 at 4:37 2014-01-14 04:37
source share