环境路径目录迭代 [英] Environment PATH Directories Iteration
本文介绍了环境路径目录迭代的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我不能找到任何代码(不是C和C ++ Boost.Filsystem)关于如何迭代(解析) PATH中存在的目录
环境变量优先以独立于平台的方式。这不是很难写,但如果可用,我想重用标准模块。链接或建议任何人?
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?
推荐答案
这是我以前使用过的:
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.
这篇关于环境路径目录迭代的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文