Remove environmental variable programmatically

生来就可爱ヽ(ⅴ<●) 提交于 2021-01-27 05:00:12

问题


I need to write a unit test for some C++ code that checks for the presence of an environmental variable. I'm using MSVS 2008 and gtest as my framework. I add the environmental variable using putenv, I check the environmental variable using getevn, but I can't figure out how to remove it so that no other test will see it. I realize this is probably easy, but I can't find the answer on the internet. Thanks


回答1:


Calling putenv again specifying "SOME_VAR=" as parameter will delete environment variable SOME_VAR. btw, Microsoft recommends using _putenv as putenv is deprecated.




回答2:


You could always fork/exec a subprocess to do just the putenv/getenv testing, and then when it terminates there isn't any stray environment left around.




回答3:


How about setting the env var to an empty string?

From cmd.exe, this works:

set SOMEVAR=something
echo %SOMEVAR%
set SOMEVAR=
echo %SOMEVAR%

Where the last one shows it has been deleted.




回答4:


you can use the unsetenv function.

If vc2008 lacks this function, you can directly access the environment using getenv_s, and remove the entry manually, simulating unsetenv.



来源:https://stackoverflow.com/questions/3205197/remove-environmental-variable-programmatically

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!