#include <QtCore>
class VarExpander
{
QString result;
int posResult;
void append(QChar c)
{
if (posResult>=result.capacity())
{
result.reserve(result.capacity() * 2);
}
result[posResult] = c;
posResult++;
}
void replaceVar(QString path, QString startTag, QString endTag, int &varCounter)
{
varCounter = 0;
int startPos = 0;
int endPos = -endTag.length();
result.reserve(path.length() * 2);
posResult = 0;
while (startPos>=0 && startPos<path.length())
{
startPos = path.indexOf(startTag,startPos);
if (startPos<0)
{
for (int i=endPos + endTag.length(); i<path.length(); i++)
append(path[i]);
break;
}
for (int i=endPos + endTag.length(); i<startPos; i++)
append(path[i]);
endPos = path.indexOf(endTag,startPos+startTag.length());
if (endPos<0)
{
for (int i=startPos + startTag.length(); i<path.length(); i++)
append(path[i]);
break;
}
QString varName = path.mid(startPos + startTag.length(),
endPos - startPos - startTag.length());
QString varValue = QString::fromStdString(qgetenv(varName.toStdString().c_str()).toStdString());
varCounter++;
for (int i=0; i<varValue.length(); i++)
append(varValue[i]);
startPos = endPos+endTag.length();
}
result.squeeze();
}
public:
VarExpander() {}
QString expand(QString path){
QString startTag, endTag;
#if defined(Q_OS_WIN)
startTag = "%", endTag = "%";
#elif defined(Q_OS_LINUX)
startTag = "${", endTag = "}";
#endif
int varCounter;
int loopCounter = 0;
do{
replaceVar(path, startTag, endTag, varCounter);
if (QString::compare(path, result, Qt::CaseInsensitive) == 0) break;
path = result;
loopCounter++;
} while (varCounter > 0 && loopCounter<10);
return path;
}
};
int main(int argc, char *argv[])
{
VarExpander ve;
QString res = ve.expand("%SystemRoot%\\system32\\wmploc.dll,-732");
printf("%s\n",res.toStdString().c_str());
}