1

環境変数に存在するディレクトリをプラットフォームに依存しない方法で反復解析)する方法に関するコード(CでもC ++ Boost.Filsystemでもない)が見つかりません。PATH書くのはそれほど難しいことではありませんが、標準モジュールが利用可能であれば再利用したいと思います。リンクや提案はありますか?

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 に答える