您的位置:首页 > 编程语言 > C语言/C++

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

2014-04-30 15:02 483 查看
在写作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
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息