expand file names that have environment variables in their path

后端 未结 8 2110
礼貌的吻别
礼貌的吻别 2020-12-01 08:06

What\'s the best way to expand

${MyPath}/filename.txt to /home/user/filename.txt

or

%MyPath%/filename.txt to c:\\Document         


        
8条回答
  •  佛祖请我去吃肉
    2020-12-01 08:36

    Simple and portable:

    #include 
    #include 
    
    static std::string expand_environment_variables( const std::string &s ) {
        if( s.find( "${" ) == std::string::npos ) return s;
    
        std::string pre  = s.substr( 0, s.find( "${" ) );
        std::string post = s.substr( s.find( "${" ) + 2 );
    
        if( post.find( '}' ) == std::string::npos ) return s;
    
        std::string variable = post.substr( 0, post.find( '}' ) );
        std::string value    = "";
    
        post = post.substr( post.find( '}' ) + 1 );
    
        const *v = getenv( variable.c_str() );
        if( v != NULL ) value = std::string( v );
    
        return expand_environment_variables( pre + value + post );
    }
    

    expand_environment_variables( "${HOME}/.myconfigfile" ); yields /home/joe/.myconfigfile

提交回复
热议问题