boost::filesystem get relative path

后端 未结 5 2131
予麋鹿
予麋鹿 2020-12-29 20:20

What methods of the boost::filesystem library can help me to get a path relative to another path?

I have a path /home/user1/Downloads/Books

5条回答
  •  借酒劲吻你
    2020-12-29 20:50

    The code in the provided answers is quite long on each line. Assuming that you wrote namespace fs = boost::filesystem; then this code gets you most of the way and looks easier to read to me:

        auto relativeTo( const fs::path& from, const fs::path& to )
        {
           // Start at the root path and while they are the same then do nothing then when they first
           // diverge take the entire from path, swap it with '..' segments, and then append the remainder of the to path.
           auto fromIter = from.begin();
           auto toIter = to.begin();
    
           // Loop through both while they are the same to find nearest common directory
           while( fromIter != from.end() && toIter != to.end() && *toIter == *fromIter )
           {
              ++toIter;
              ++fromIter;
           }
    
           // Replace from path segments with '..' (from => nearest common directory)
           auto finalPath = fs::path{};
           while( fromIter != from.end() )
           {
              finalPath /= "..";
              ++fromIter;
           }
    
           // Append the remainder of the to path (nearest common directory => to)
           while( toIter != to.end() )
           {
              finalPath /= *toIter;
              ++toIter;
           }
    
           return finalPath;
        }
    

提交回复
热议问题