system() 中的变量调用 C++

variables in system() call C++

我在 argv[1] 中有一个变量,我需要以这种方式在另一个 c++ 文件中调用它:

        system("./assemblerL.out", argv[1]);

上面的语法不正确,因为我收到 "too many arguments" 错误。

正确的做法是什么?

尝试将命令连接成一个字符串,然后像这样调用系统:

char ch[50]="";
strcat(ch,"./assemblerL.out ");
strcat(ch,argv[1]);
system(ch); 

system 只能带一个参数,就像在 shell
中输入的那样是一整行 (好吧,不是像 Bash 这样的 shell 得到的所有东西,但这在这里并不重要)。

对于 C++,只需使用 std::string 连接部分:

system((std::string("./assemblerL.out ") + argv[1]).c_str());  

或者,更具可读性:

std::string line = "./assemblerL.out ";
line += argv[1];
system(line.c_str());  

记得在使用前确保 argv[1] 存在。

std::system只带一个参数,必须是你要执行的完整字符串。请注意,如果这是 Linux,结果是通过调用子 shell 实现的,因此可能会出现 expansion/substitution。您可能需要考虑 exec 函数行。对于 Windows,您可能需要调查 CreateProcess。

您有多种构建命令行的选择:

// c-like
char buffer[1024];
snprintf(buffer, sizeof(buffer), "%s %s", "command", "argument");
system(buffer); // could be truncated

// c++ string based
std::string commandline = std::string(command) + std::string(argument);
system(commandline.c_str());

// stringbuffer
#include <sstream>
std::ostringstream buf;
buf << command << " " << argument;
system(buf.str().c_str());