boost::filesystem get relative path

后端 未结 5 2127
予麋鹿
予麋鹿 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:30

    The accepted answer's code doesn't work. It should be

    namespace boost { namespace filesystem {
    
    template <> path& path::append(path::iterator begin, path::iterator end, const codecvt_type& cvt)
    {
        for( ; begin != end ; ++begin )
            *this /= *begin;
        return *this;
    }
    
    // Return path when appended to a_From will resolve to same as a_To
    boost::filesystem::path make_relative( boost::filesystem::path a_From, boost::filesystem::path a_To )
    {
        a_From = boost::filesystem::absolute( a_From ); a_To = boost::filesystem::absolute( a_To );
        boost::filesystem::path ret;
        boost::filesystem::path::const_iterator itrFrom( a_From.begin() ), itrTo( a_To.begin() );
        // Find common base
        for( boost::filesystem::path::const_iterator toEnd( a_To.end() ), fromEnd( a_From.end() ) ; itrFrom != fromEnd && itrTo != toEnd && *itrFrom == *itrTo; ++itrFrom, ++itrTo );
        // Navigate backwards in directory to reach previously found base
        for( boost::filesystem::path::const_iterator fromEnd( a_From.end() ); itrFrom != fromEnd; ++itrFrom )
        {
            if( (*itrFrom) != "." )
                ret /= "..";
        }
        // Now navigate down the directory branch
        ret.append( itrTo, a_To.end() );
        return ret;
    }
    
    } } // namespace boost::filesystem
    

提交回复
热议问题