![](/img/trans.png)
[英]Set current user environment variable from c++ code visible to other process like cmds
[英]Set environment variable in Windows with c++ that is visible to subprocess
我想知道如何從 c++ 程序中設置環境變量。 我有一些要求。
示例虛擬應用程序
void setVariable(std::string name, std::string value) {
// This is what I dont know how to do.
}
int main(int, char **) {
setVariable("hello", "there");
system("echo %hello%");
}
我已經嘗試過_putenv
,但是我的子進程在設置變量后似乎沒有找到它。 而且我沒有找到任何示例如何將std::string
轉換為SetEnvironmentVariable的輸入
您可以使用_putenv_s
設置環境變量:
#include <cstdlib>
void setVariable(std::string name, std::string value) {
_putenv_s(name.c_str(), value.c_str());
}
// if you need a wide version:
void setVariable(std::wstring name, std::wstring value) {
_wputenv_s(name.c_str(), value.c_str());
}
int main() {
setVariable("hello", "there");
std::system("echo %hello%");
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.