c++中如何执行cmd命令并获取输出

avatar
作者
猴君
阅读量:0

在C++中,你可以使用popen()函数来执行CMD命令并获取其输出

#include<iostream> #include<string> #include <cstdio>  std::string exec_cmd(const char* cmd) {     std::string result;     char buffer[128];     FILE* pipe = popen(cmd, "r");          if (pipe != nullptr) {         while (fgets(buffer, sizeof(buffer), pipe) != nullptr) {             result += buffer;         }                  pclose(pipe);     } else {         throw std::runtime_error("popen() failed!");     }          return result; }  int main() {     try {         std::string output = exec_cmd("ipconfig"); // 将你想要执行的CMD命令替换为"ipconfig"         std::cout << "Command output: "<< std::endl<< output<< std::endl;     } catch (const std::exception& e) {         std::cerr << "Error: " << e.what()<< std::endl;     }          return 0; } 

这个示例代码定义了一个名为exec_cmd()的函数,该函数接受一个CMD命令字符串作为参数。然后,它使用popen()函数执行命令并读取输出。最后,将输出作为std::string返回。

main()函数中,我们调用exec_cmd()函数并传入我们想要执行的CMD命令(在这个例子中是ipconfig)。然后,我们将命令的输出打印到控制台。

请注意,这个示例代码仅适用于Unix-like系统(如Linux和macOS)。如果你正在使用Windows系统,你需要将popen()pclose()替换为_popen()_pclose(),并包含<windows.h>头文件。

广告一刻

为您即时展示最新活动产品广告消息,让您随时掌握产品活动新动态!