微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

使用对子进程可见的 c++ 在 Windows 中设置环境变量

如何解决使用对子进程可见的 c++ 在 Windows 中设置环境变量

我想知道如何从 C++ 程序设置环境变量。我有一些要求。

  • 它需要对使用 std::system() 启动的子进程可见
  • 它需要在 Windows 中工作
  • 它需要很好地与 std::string 接口

示例虚拟应用程序

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%");
}

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。