[英]Using getenv() to read environment variable returns NULL C++
I am attempting to read an environment variable in C++ as per this documentation . 我正在尝试根据本文档阅读C ++中的环境变量。 My code looks like this:
我的代码如下所示:
char * val;
val = getenv( "smartDir" );
ShowMessage( val );
delete val;
My problem is that val always ends up NULL as if the enviroment variable does not exist. 我的问题是,val总是以NULL结尾,就像环境变量不存在一样。 However, I clearly have the variable defined as you can see here:
但是,我清楚地定义了变量,如下所示:
What am I doing wrong here? 我在这里做错了什么?
getenv
(see here , part about undefined behavior) getenv
返回的指针(请参阅此处 ,有关未定义行为的部分) To make testing easier: most IDEs provide 'Environment' setting under 'Debugging' settings - you can change there env passed to child process (your program) (Visual has it, QtCreator has it, C++Builder probably has it also etc.) 为了简化测试:大多数IDE在“调试”设置下提供“环境”设置-您可以更改传递给子进程(您的程序)的env(Visual拥有它,QtCreator拥有它,C ++ Builder可能也具有它等等)。 )
If you execute your program from console: use SET var=value
instead of changing global env, to make local change before passing env to child process. 如果从控制台执行程序,请执行以下操作:在将env传递给子进程之前,请使用
SET var=value
而不是更改全局env进行本地更改。
Both solutions do not modify global env and allow to quickly test different env settings. 两种解决方案都不会修改全局环境,而是允许快速测试不同的环境设置。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.