holyya.com
2025-09-04 14:51:33 Thursday
登录
文章检索 我的文章 写文章
C++中如何将system命令的结果存入字符串中?
2023-07-05 09:29:20 深夜i     --     --
C++ system命令 结果 存储 字符串

C++是一种程序设计语言,常用于开发操作系统、嵌入式系统以及大型应用程序。其语言规范对于系统操作也提供了方便。

在C++中,有时需要执行系统命令,并将其返回的结果存入字符串中,这时可以使用system函数。而如何将system命令的结果存入字符串中,是C++程序设计时常见的一个问题。

下面介绍两种方法:

1.使用popen函数

popen函数可以调用不同的程序,通过管道可以与它交换信息。在C++中,可以使用popen函数以读方式打开一个进程并通过管道读取该进程的输出信息,代码如下:


#include <stdio.h>

#include <stdlib.h>

#include <string.h>

#define BUFSIZE 256

using namespace std;

string exec(char* cmd) {

  char buffer[BUFSIZE];

  string result;

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

  if (!pipe)

    throw runtime_error("popen() failed!");

  try {

    while (fgets(buffer, BUFSIZE, pipe) != NULL)

      result += buffer;

  } catch (...) {

    pclose(pipe);

    throw;

  }

  pclose(pipe);

  return result;

}

int main(void) {

  string result = exec("system command here");

  cout << result << endl;

  return 0;

}

2.使用stringstream

在C++中,stringstream类是一个用来读写字符串的流,它类似于缓冲区流和文件流。使用它,可以将system命令的结果存储在一个string变量中,代码如下:


#include <iostream>

#include <string>

#include <sstream>

#include <stdio.h>

using namespace std;

string exec(char* cmd) {

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

  if (!pipe)

    return string("popen() failed!");

  char buffer[128];

  string result = "";

  while (!feof(pipe)) {

    if (fgets(buffer, 128, pipe) != NULL)

      result += buffer;

  }

  pclose(pipe);

  return result;

}

int main() {

  string result = exec("system command here");

  stringstream ss(result);

  string token;

  while (getline(ss, token, '\n'))

    cout << token << endl;

  

  return 0;

}

综上,以上两种方法都是将system命令的结果存入字符串中的有效方法。根据实际需要选择其中一种即可。

  
  

评论区

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