expand file names that have environment variables in their path

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

    Using Qt, this works for me:

    #include 
    #include 
    
    QString expand_environment_variables( QString s )
    {
        QString r(s);
        QRegExp env_var("\\$([A-Za-z0-9_]+)");
        int i;
    
        while((i = env_var.indexIn(r)) != -1) {
            QByteArray value(qgetenv(env_var.cap(1).toLatin1().data()));
            if(value.size() > 0) {
                r.remove(i, env_var.matchedLength());
                r.insert(i, value);
            } else
                break;
        }
        return r;
    }
    

    expand_environment_variables(QString("$HOME/.myconfigfile")); yields /home/martin/.myconfigfile (It also works with nested expansions)

提交回复
热议问题