2015-10-19 96 views
5

boost::filesystem是否有扩展以用户主目录符号(Unix上的~)开头的路径的功能,类似于Python中提供的os.path.expanduser函数?使用boost :: filesystem扩展用户路径

+0

您是否尝试过使用http://www.boost.org/doc/libs/1_48_0/libs/filesystem/v3/doc/reference.html#canonical? – Hamdor

+0

@Hamdor我确实尝试过类似'canonical(path(“〜/ test.txt”))',但那并不奏效。使用不正确? – Daniel

+0

我怀疑是否有。但也请参阅http://stackoverflow.com/questions/4891006/how-to-create-a-folder-in-the-home-directory – WhiteViking

回答

4

但是你可以做这样实现:

namespace bfs = boost::filesystem; 
    using std; 

    bfs::path expand (bfs::path in) { 
    if (in.size() < 1) return in; 

    const char * home = getenv ("HOME"); 
    if (home == NULL) { 
     cerr << "error: HOME variable not set." << endl; 
     throw std::invalid_argument ("error: HOME environment variable not set."); 
    } 

    string s = in.c_str(); 
    if (s[0] == '~') { 
     s = string(home) + s.substr (1, s.size() - 1); 
     return bfs::path (s); 
    } else { 
     return in; 
    } 
    } 

而且,看看通过@WhiteViking建议similar question

相关问题