1 获取CMD中字符串的输出:
#define _CRT_SECURE_NO_WARNINGS
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
void getCMD(char *in, char *out)
{
char buffer[128] = { 0 };
FILE *pipe = _popen(in, "r"); //获取命令行的输入,并执行,pipe相当于一个管道
if (!pipe)
exit(-1);
while (!feof(pipe)) //判断文件是否结束
{
if (fgets(buffer, 128, pipe)) //从管道中读取数据
{
strcat(out, buffer);
}
}
_pclose(pipe); //关闭该管道
}
void main()
{
FILE *my_out = fopen("out.txt", "w");
if (!my_out)
exit(-1);
char CMDin[50] = { 0 };
char CMDout[4096] = { 0 };
scanf("%s", CMDin);
getCMD(CMDin, CMDout);
printf("打印输出:%s", CMDout);
printf("\nstrlen(CMDout) = %d\n", strlen(CMDout));
fprintf(my_out, "%s", CMDout);
fclose(my_out);
system("pause");
}
在out.txt中将会出现和CMD中一样的输出字符串。