1

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

4

2 回答 2

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

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

于 2012-07-02T14:22:04.150 回答
0

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

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
于 2016-12-03T07:17:24.303 回答