环境路径目录迭代

Environment PATH Directories Iteration

本文关键字:迭代 路径 环境      更新时间:2023-10-16

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

这是我

之前使用的:

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

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

这是我自己的代码片段,没有高级提升库:

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