【问题标题】:Environment PATH Directories Iteration环境路径目录迭代
【发布时间】:2012-07-02 22:43:25
【问题描述】:

我找不到关于如何迭代解析PATH 环境变量中存在的目录的任何代码(C 和 C++ Boost.Filsystem)最好以独立于平台的方式。编写起来并不难,但如果标准模块可用,我想重用它们。任何人的链接或建议?

【问题讨论】:

  • 您的意思是从PATH 中提取目录以得到目录列表吗?如果是这样,您可以在 unix 上使用 boost::split() 并使用 : 在 windows 上使用 ; 作为分隔符。
  • @hmjd 太好了,这行得通!然而,从 C++ 算法风格的角度来看,Boost 的 split_iterator<string::iterator> 更加优雅。谢谢。见boost.org/doc/libs/1_49_0/doc/html/string_algo/…

标签: c++ parsing path environment-variables boost-filesystem


【解决方案1】:

这是我之前用过的:

const vector<string>& get_environment_PATH()
{
    static vector<string> result;
    if( !result.empty() )
        return result;

#if _WIN32
    const std::string PATH = convert_to_utf8( _wgetenv(L"PATH") ); // Handle Unicode, just remove if you don't want/need this. convert_to_utf8 uses WideCharToMultiByte in the Win32 API
    const char delimiter = ';';
#else
    const std::string PATH = getenv( "PATH" );
    const char delimiter = ':';
#endif
    if( PATH.empty() )
        throw runtime_error( "PATH should not be empty" );

    size_t previous = 0;
    size_t index = PATH.find( delimiter );
    while( index != string::npos )
    {
        result.push_back( PATH.substr(previous, index-previous));
        previous=index+1;
        index = PATH.find( delimiter, previous );
    }
    result.push_back( PATH.substr(previous) );

    return result;
}

这只会在每个程序运行时“计算”一次。它也不是真正的线程安全,但见鬼,与环境无关。

【讨论】:

    【解决方案2】:

    这是我自己的代码 sn-p 没有高级 boost 库:

    if( exe.GetLength() )
    {
        wchar_t* pathEnvVariable = _wgetenv(L"PATH");
    
        for( wchar_t* pPath = wcstok( pathEnvVariable, L";" ) ; pPath ; pPath = wcstok( nullptr, L";" ) )
        {
            CStringW exePath = pPath;
            exePath += L"\\";
            exePath += exe;
    
            if( PathFileExists(exePath) )
            {
                exe = exePath;
                break;
            }
        } //for
    } //if
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-10-23
      • 2011-08-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多