C++中,如何执行一个控制台命令并返回结果到字符串string中

来源:互联网 发布:java工作日报 编辑:程序博客网 时间:2024/06/17 01:17

在写作c、c++控制台程序时,我们可以直接调用控制台下的命令,在控制台上输出一些信息。

调用方式为 system(char*);

例如,在控制台程序中,获得本机网络配置情况。

int main(){

system("ipconfig");

return 0;

}

但是,如果我们想保存调用命令的输出结果呢?

这里给大家介绍一种方法:

#include <string>#include <iostream>#include <stdio.h>std::string exec(char* cmd) {    FILE* pipe = popen(cmd, "r");    if (!pipe) return "ERROR";    char buffer[128];    std::string result = "";    while(!feof(pipe)) {    if(fgets(buffer, 128, pipe) != NULL)    result += buffer;    }    pclose(pipe);    return result;}
如果是在windows系统下,请用_popen, _pclose替换popen, pclose。

这个函数中,输入的是命令的名字,返回的是执行的结果。

从一个国外网站上看来的:http://stackoverflow.com/questions/478898/how-to-execute-a-command-and-get-output-of-command-within-c

0 0
原创粉丝点击