如何在C++ CLI中执行两条命令并获取命令输出?
在C++ CLI中执行切换目录并调用exe,同时打印输出
我有一个C应用程序,现有两条命令字符串:一条用于切换目录,另一条用于调用.exe文件。我希望在C项目的CLI中打印该命令的输出。
现有代码
std::string cd = "cd " + pathToExe; std::string cmd = "file.exe" + comport + " " + com + " turn " + angle;
错误尝试及问题
尝试1
system(cd.c_str() && cmd.c_str());
报错:argument of type "bool" is incompatible with parameter of type "const char *"
原因:&&是逻辑运算符,会把两个指针转换为布尔值计算,最终传入system()的是布尔值,不符合函数参数要求。
尝试2
system(cd.c_str(); cmd.c_str());
报错:expected a ')' and expected a ';'
原因:system()仅接受一个参数,该写法存在语法错误。
解决方案
system()函数仅支持传入单个命令字符串,要执行多条命令需按shell语法合并,或直接切换进程工作目录:
方案1:合并命令(Windows cmd环境)
用&&连接两条命令(前一条执行成功才会执行后一条),合并为单个字符串后传入system():
std::string full_cmd = cd + " && " + cmd; system(full_cmd.c_str());
执行后,exe的输出会直接打印到CLI窗口中。如果不需要依赖前一条命令的执行结果,可改用&连接。
方案2:切换进程工作目录(跨平台/更可靠)
不依赖shell命令拼接,直接修改当前进程的工作目录后调用exe:
- Windows平台API:
#include <direct.h> // 切换到目标目录 _chdir(pathToExe.c_str()); // 执行exe命令 system(cmd.c_str());
- C++17跨平台方案(需链接filesystem库):
#include <filesystem> namespace fs = std::filesystem; // 切换工作目录 fs::current_path(pathToExe); // 执行exe命令 system(cmd.c_str());
内容的提问来源于stack exchange,提问作者mallocFreestyle
相关产品推荐
相关产品推荐

