2014-03-03 96 views
0

我需要一個函數來獲取絕對路徑,爲此目的,我在boost中查看了一下,但它只在最近的版本和中有,我使用的是舊1.44。由於我無法在最近的升級版本1.55或更高版本上更新我的代碼,因此我決定重新編寫該函數。 它在Windows上工作正常,但我在Linux下無限遞歸,我不明白爲什麼?該代碼是基於你可以找到的描述here當我使用boost建立絕對路徑時無限遞歸

所有的建議,以解決這個問題將受到歡迎! 感謝

#include "boost/filesystem.hpp" 
namespace bfs = boost::filesystem; 

inline bfs::path absolute(const bfs::path& p, const bfs::path& base=bfs::current_path()) 
{ 
    if(p.has_root_directory()) 
    { 
    if(p.has_root_name()) return p; 
    else return absolute(base).root_name()/p; 
    } 
    else 
    { 
    if(p.has_root_name()) return bfs::path(p.root_name())/bfs::path(absolute(base).root_directory())/absolute(base).relative_path()/p.relative_path(); 
    else return absolute(base)/p; 
    } 
} 

回答

0

最後,我用升壓v1.55代碼的副本來解決這個問題。

inline bool is_absolute(const bfs::path p) 
{ 
#if defined(WIN32) || defined(WIN64) 
    return p.has_root_name() && p.has_root_directory(); 
#else 
    return p.has_root_directory(); 
#endif 
} 

inline bfs::path absolute(const bfs::path& p, const bfs::path& base=bfs::current_path()) 
{ 
    // recursively calling absolute is sub-optimal, but is sure and simple 
    bfs::path abs_base(is_absolute(base) ? base : absolute(base)); 

    // store expensive to compute values that are needed multiple times 
    bfs::path p_root_name (p.root_name()); 
    bfs::path base_root_name (abs_base.root_name()); 
    bfs::path p_root_directory (p.root_directory()); 

    if (p.empty()) 
    { 
    return abs_base; 
    } 

    if (!p_root_name.empty()) // p.has_root_name() 
    { 
    if (p_root_directory.empty()) // !p.has_root_directory() 
     return p_root_name/abs_base.root_directory() 
    /abs_base.relative_path()/p.relative_path(); 
    // p is absolute, so fall through to return p at end of block 
    } 
    else if (!p_root_directory.empty()) // p.has_root_directory() 
    { 
    return base_root_name/p; 
    } 
    else 
    { 
    return abs_base/p; 
    } 

    return p; // p.is_absolute() is true 
}