展开其路径中包含环境变量的文件名

时间:2009-12-14 18:39:31

标签: c++ wxwidgets boost-filesystem

什么是扩展的最佳方式

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

%MyPath%/filename.txt to c:\Documents and settings\user\filename.txt

没有遍历路径字符串直接查找environement变量? 我看到wxWidgets有一个wxExpandEnvVars函数。在这种情况下我不能使用wxWidgets,所以我希望找到一个boost :: filesystem等价或类似的。我只使用主目录作为示例,我正在寻找通用路径扩展。

9 个答案:

答案 0 :(得分:23)

对于UNIX(或至少POSIX)系统,请查看wordexp

#include <iostream>
#include <wordexp.h>
using namespace std;
int main() {
  wordexp_t p;
  char** w;
  wordexp( "$HOME/bin", &p, 0 );
  w = p.we_wordv;
  for (size_t i=0; i<p.we_wordc;i++ ) cout << w[i] << endl;
  wordfree( &p );
  return 0;
}

它似乎甚至会做类似于全球的扩展(对你的特定情况可能有用,也可能没有用)。

答案 1 :(得分:17)

在Windows上,您可以使用ExpandEnvironmentStrings。还不确定Unix等价物。

答案 2 :(得分:9)

如果你有使用C ++ 11的奢侈,那么正则表达式非常方便。我写了一个用于更新的版本和一个声明版本。

#include <string>
#include <regex>

// 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;
}

这种方法的一个优点是它可以很容易地适应语法变化并处理宽字符串。 (在OS X上使用Clang进行编译和测试,标志为-std = c ++ 0x)

答案 3 :(得分:6)

简单易用:

#include <cstdlib>
#include <string>

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" );收益/home/joe/.myconfigfile

答案 4 :(得分:3)

在C / C ++语言中,这是我在Unix下解决环境变量的方法。 fs_parm指针将包含要扩展的可能环境变量的filespec(或文本)。 wrkSpc指向的空间必须是MAX_PATH + 60个字符长。 echo字符串中的双引号用于防止处理通配符。大多数默认shell应该能够处理这个问题。


   FILE *fp1;

   sprintf(wrkSpc, "echo \"%s\" 2>/dev/null", fs_parm);
   if ((fp1 = popen(wrkSpc, "r")) == NULL || /* do echo cmd     */
       fgets(wrkSpc, MAX_NAME, fp1) == NULL)/* Get echo results */
   {                        /* open/get pipe failed             */
     pclose(fp1);           /* close pipe                       */
     return (P_ERROR);      /* pipe function failed             */
   }
   pclose(fp1);             /* close pipe                       */
   wrkSpc[strlen(wrkSpc)-1] = '\0';/* remove newline            */

对于MS Windows,请使用ExpandEnvironmentStrings()函数。

答案 5 :(得分:1)

这就是我使用的:

const unsigned short expandEnvVars(std::string& original)
{
    const boost::regex envscan("%([0-9A-Za-z\\/]*)%");
    const boost::sregex_iterator end;
    typedef std::list<std::tuple<const std::string,const std::string>> t2StrLst;
    t2StrLst replacements;
    for (boost::sregex_iterator rit(original.begin(), original.end(), envscan); rit != end; ++rit)
        replacements.push_back(std::make_pair((*rit)[0],(*rit)[1]));
    unsigned short cnt = 0;
    for (t2StrLst::const_iterator lit = replacements.begin(); lit != replacements.end(); ++lit)
    {
        const char* expanded = std::getenv(std::get<1>(*lit).c_str());
        if (expanded == NULL)
            continue;
        boost::replace_all(original, std::get<0>(*lit), expanded);
        cnt++;
    }
    return cnt;
}

答案 6 :(得分:1)

由于问题标记为“wxWidgets”,您可以使用wxConfig使用的wxExpandEnvVars()函数进行环境变量扩展。遗憾的是,函数本身没有记录,但它基本上按照您的想法进行,并在所有平台和$VAR下扩展$(VAR)${VAR}%VAR%的任何出现次数。仅限Windows。

答案 7 :(得分:0)

由于问题标记为C ++,您可以使用标准getenv,只需使用标准C ++ 11 regex即可将变量替换为其值。

答案 8 :(得分:0)

使用Qt,这对我有用:

#include <QString>
#include <QRegExp>

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的(&#34; $ HOME / .myconfigfile&#34));产量/home/martin/.myconfigfile (它也适用于嵌套扩展)

相关问题