1 #include
2 #include
3 #include
4 int execmd(char cmd[],char* result)
5 {
6 char buffer[128]; //定义缓冲区
7 FILE* pipe = _popen(cmd, "r"); //打开管道,并执行命令
8 if (!pipe) return 0; //返回0表示运行失败
9 while(!feof(pipe)) {
10 if(fgets(buffer, 128, pipe)){ //将管道输出到result中
11 strcat(result,buffer);
12 }
13 }
14 _pclose(pipe); //关闭管道
15 return 1; //返回1表示运行成功
16 }
17
18 void main(){
19 char result[1024*4]="";
20 char com[1024];
21 scanf("%s",com);
22 if(1==execmd(com,result))
23 {
24 printf(result);
25 }
26 }
这个是根据网上找的一个稍微改动变成的。运行后输入一个CMD命令可以返回结果,比如ipconfig,命令行详细参见HELP。
很奇怪主函数当时我写的是int没有返回值居然没有报错。。。临时改成void的、、
还有一个很奇怪的就是FILE* pipe = _popen(cmd, "r"); 这个函数,放到MFC中会一直返回空!。。。。
来源:https://www.cnblogs.com/redyoung/p/3439935.html