expand file names that have environment variables in their path

后端 未结 8 2092
礼貌的吻别
礼貌的吻别 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:37

    If you have the luxury of using C++11, then regular expressions are quite handy. I wrote a version for updating in place and a declarative version.

    #include 
    #include 
    
    // Update the input string.
    void autoExpandEnvironmentVariables( std::string & text ) {
        static std::regex env( "\\$\\{([^}]+)\\}" );
        std::smatch match;
        while ( std::regex_search( text, match, env ) ) {
            const char * s = getenv( match[1].str().c_str() );
            const std::string var( s == NULL ? "" : s );
            text.replace( match[0].first, match[0].second, var );
        }
    }
    
    // Leave input alone and return new string.
    std::string expandEnvironmentVariables( const std::string & input ) {
        std::string text = input;
        autoExpandEnvironmentVariables( text );
        return text;
    }
    

    An advantage of this approach is that it can be adapted easily to cope with syntactic variations and deal with wide strings too. (Compiled and tested using Clang on OS X with the flag -std=c++0x)

提交回复
热议问题