如何使用system()函数[C ++]在C ++中存储cmd内存 [英] How to Store cmd memory in c++ using system() Function [C++]
问题描述
看下面的代码!您将了解我想要的:
Look at the code below! You will understand what I want:
#include <iostream>
#include <windows.h>
using namespace std;
int main()
{
system("set plock=24865");
system("echo %plock%"); // I know this will not work.But How to make it work?
return 0;
}
推荐答案
嗯,正如您所说,那行不通。重要的是要理解为什么:: system
调用会生成一个子进程来运行Shell,然后设置环境变量在该子进程中,该进程立即终止。
Well, as you say, that won't work. What's important to understand is why: The system
call spawns a child process to run the shell, and then you're setting an environment variable in that child process, which promptly terminates.
因此,您的问题可能过于具体,因为它询问如何使用 system()
;简短的答案是你不能。 (答案很长,您可以在注册表中设置环境变量,但是仅当您打算将其作为对计算机的永久配置更改时才有意义。如果您只是想设置一个变量以供后续 system()
来自同一程序的调用..)
So perhaps your question is over-specific in that it asks how to do this "using system()
"; short answer is you can't. (Long answer is you could set the environment variable in the registry, but that's only sensible if you intend this to be a permanent configuration change to the computer. It's not the best idea if you just mean to set a variable for use in subsequent system()
calls from the same program..)
因此,您可以使用 SetEnvironmentVariable()
函数,它将在您当前的过程中(而不是在即将消失的孩子中)设置环境变量。
So instead you could use the SetEnvironmentVariable()
function, which will set the environment variable in your current process (instead of in a child that's about to go away).
更新-在问题的注释线程中还提到了另一个选项;但它假定您可以设置变量并立即运行依赖于此变量的任何/所有命令。在这种情况下,您可以将所有命令打包到一个系统
调用中,最简单的方法是使用批处理脚本...
UPDATE - There is one other option, alluded to in the question's comment thread; but it assumes that you can set the variable and immediately run any/all commands that depend on it right after. In the case where you can do that, you could pack all the commands into one system
call, most simply with a batch script...
这篇关于如何使用system()函数[C ++]在C ++中存储cmd内存的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!