Environment PATH Directories Iteration

2019-08-19 05:09发布

I cant find any code (neither C nor C++ Boost.Filsystem) on how to iterate (parse) the directories present in the PATH environment variable in preferrably in a platform-independent way. It is not so hard to write but I want to reuse standard modules if they are available. Links or suggestions anyone?

2条回答
神经病院院长
2楼-- · 2019-08-19 05:19

Here is my own code snippet without advanced boost libraries:

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
查看更多
聊天终结者
3楼-- · 2019-08-19 05:21

This is what I used before:

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

This only "calculates" the thing once per program run. It's not really thread-safe either, but heck, nothing environment-related is.

查看更多
登录 后发表回答