21xrx.com
2024-09-20 05:50:32 Friday
登录
文章检索 我的文章 写文章
如何在C++中获取CMD命令的返回结果
2023-07-01 08:21:42 深夜i     --     --
C++ CMD命令 返回结果 获取

在C++中,使用system函数可以执行CMD命令,但是如何获取这个命令的返回结果呢?本文将介绍如何在C++中获取CMD命令的返回结果。

方法一:使用文件

可以将CMD命令的返回数据写入到一个文件中,然后读取文件内容作为返回结果。具体的实现方法如下:


#include <iostream>

#include <fstream>

#include <cstdlib>

using namespace std;

int main() {

  system("dir > result.txt"); // 执行CMD命令

  ifstream fin("result.txt"); // 打开结果文件

  string line;

  while (getline(fin, line)) // 逐行读取文件内容

    cout << line << endl; // 输出文件内容到屏幕

  

  fin.close(); // 关闭文件

  return 0;

}

上述示例中,我们使用了系统调用中的system函数来执行CMD命令,并将CMD命令的返回结果写入到了result.txt文件中。然后我们打开文件并逐行读取文件内容,将读取到的内容输出到屏幕上。

方法二:使用管道

另一种更加高效的方式是使用管道来获取CMD命令的返回结果。具体的实现方法如下:


#include <iostream>

#include <algorithm>

#include <cstdio>

#include <iostream>

#include <string>

#include <stdlib.h>

#ifdef _WIN32

#include <Windows.h>

#else

#include <unistd.h> // Unix/Linux

#endif

using namespace std;

string execCommand(const char* cmd) {

#ifdef _WIN32

  // Windows

  char buffer[128];

  string result = "";

  FILE* pipe = _popen(cmd, "r");

  if (!pipe)

    return "popen failed!";

  

  while (fgets(buffer, sizeof(buffer), pipe) != NULL) {

    result += buffer;

  }

  _pclose(pipe);

  return result;

#else

  // Unix/Linux

  char buffer[128];

  string result = "";

  FILE* pipe = popen(cmd, "r");

  if (!pipe)

    return "popen failed!";

  

  while (fgets(buffer, sizeof(buffer), pipe) != NULL) {

    result += buffer;

  }

  pclose(pipe);

  return result;

#endif

}

int main() {

  cout << "Result: " << execCommand("dir").c_str() << endl;

  return 0;

}

上述示例中,我们通过执行CMD命令并读取其输出来获取CMD命令的返回结果。我们使用了系统调用中的popen函数来打开一个管道,并将CMD命令作为参数传递给该管道。然后,我们使用fgets函数来读取管道中的输出内容,并将其保存到字符串中最终输出到控制台。最后我们关闭管道。

结论

本文介绍了两种方法来在C++中获取CMD命令的返回结果。使用文件的方法比较简单,但是不够高效;使用管道的方法则更加高效。根据应用场景的不同,读者可以选择适合自己的方法。

  
  

评论区

{{item['qq_nickname']}}
()
回复
回复