管道小实例

_popen函数:建立管道IO。

定义:

FILE * popen ( const char * command , const char * type );

_pclose函数:关闭管道。

例子,将输入放进cmd.exe中,并获取结果。

 1 #define  _CRT_SECURE_NO_WARNINGS
 2 #include<stdio.h>
 3 #include<stdlib.h>
 4 #include<string.h>
 5 #include<Windows.h>
 6 
 7 int exeshell(char *cmd)
 8 {
 9     FILE *fp = _popen(cmd, "r");    //创建管道
10     if (fp == NULL) {
11         printf("打开管道失败\n");
12         return 0;
13     }
14     else {
15         while(!feof(fp)) {
16             char str[256] = { 0 };
17             if (fgets(str, 256, fp)) {
18                 printf("%s",str);
19             }
20         }
21         return 0;
22     }
23     _pclose(fp);    //关闭管道
24 }
25 
26 int main() {
27     char s[256] = { 0 };
28     while (scanf("%s", &s) != EOF)
29         exeshell(s);
30     system("pause>nul");
31     return 0;
32 }
原文地址:https://www.cnblogs.com/HadesBlog/p/7668235.html