从 C++ 设置系统变量 [英] Set system variable from C++

查看:57
本文介绍了从 C++ 设置系统变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这个shell脚本

#!/bin/csh
set VAR=12345
echo $VAR

将在 shell 中和平地给出输出 12345.我需要在代码的某些部分使用 C++ 来做同样的事情:

will peacefully give the output 12345 at shell. I need to use C++ to do the same in some part of the code:

string str = "12345";
retValue="set var1= "+str;      
system(retValue1.c_str());
system("echo $var1");

这不会创建系统变量 var1 并回显 null,这是可以理解的,因为每个系统函数都会创建一个具有不同环境变量的子进程.所以我只使用一个系统函数将它们组合如下......但它再次回显 null.

This doesn't create a system variable var1 and echos null which is understandable as each system function would create a child process with different environment variables. So I combine them as follows using just one system function...but it echos null again.

retValue="set var1= "+str;
retValue1=retValue+";\n echo $var1";
system(retValue1.c_str());

有人可以指导我通过 C++ 设置系统变量吗?提前非常感谢!

Can someone please guide me to set up the system variable thru C++. Thanks a lot in advance!

推荐答案

查看中的setenv:

#include <cstdlib>

setenv("VAR", "12345", true);

这篇关于从 C++ 设置系统变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆