环境路径目录迭代

时间:2012-07-02 13:48:32

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

我找不到任何代码(C和C ++ Boost.Filsystem)如何迭代解析PATH环境变量中存在的目录优选地,以平台无关的方式。写起来并不难,但我希望重用标准模块(如果有的话)。任何人的链接或建议?

2 个答案:

答案 0 :(得分: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;
}

这只是每次程序运行时“计算”一次。它也不是真正的线程安全,但是,没有任何与环境相关的东西。

答案 1 :(得分:0)

这是我自己的代码片段,没有高级的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