popen()函数详解
popen()函数
1 /*============================================ 2 > Copyright (C) 2014 All rights reserved. 3 > FileName:popen.c 4 > author:donald 5 > date:2014/08/22/ 12:20:53 6 > details: 7 ==============================================*/ 8 #include <unistd.h> 9 #include <stdio.h> 10 #include <stdlib.h> 11 #include <string.h> 12 #define N 512 13 int main(int argc, const char *argv[]) 14 { 15 FILE *fp; 16 char cmd[N],buf[N]; 17 memset(cmd,0,N); 18 memset(buf,0,N); 19 #if 0 20 fgets(cmd,N,stdin); 21 fp = popen(cmd,"r"); 22 while(fgets(buf,N,fp) != NULL) 23 printf("%s",buf); 24 #endif 25 #if 1 26 fgets(cmd,N,stdin); 27 fp = popen(cmd,"w"); 28 //这里把用户输入写进了cmd, 29 if(fp == NULL) 30 printf("error\n"); 31 fgets(buf,N,fp); 32 printf("123%s\n",buf);//测试时使用 33 #endif 34 pclose(fp); 35 return 0; 36 }
open_mode为“r”
open_mode为“w”
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 /*============================================ 2 > Copyright (C) 2014 All rights reserved. 3 > FileName:my_ponen.c 4 > author:donald 5 > details: 6 ==============================================*/ 7 #include <unistd.h> 8 #include <stdio.h> 9 #include <stdlib.h> 10 #include <string.h> 11 int main(int argc, const char *argv[]) 12 { 13 int left,right,sum; 14 FILE* fp ; 15 char cmd[1024] = ""; 16 while(1){ 17 scanf("%d%d",&left,&right); 18 sprintf(cmd,"%s %d %d",argv[1],left,right); 19 fp = popen(cmd,"r"); 20 fscanf(fp,"%d",&sum); 21 printf("result is : %d\n",sum); 22 23 pclose(fp); 24 } 25 return 0; 26 }
目标函数
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 /*============================================ 2 > Copyright (C) 2014 All rights reserved. 3 > FileName:mystring.c 4 > author:donald 5 > details: 6 ==============================================*/ 7 #include <stdio.h> 8 #include <stdlib.h> 9 #include <string.h> 10 #define N 1024 11 int main(int argc, const char *argv[]) 12 { 13 int index; 14 char buf[N]; 15 memset(buf,0,N); 16 for(index = argc - 1;index > 0;index --){ 17 strcat(buf,argv[index]); 18 strcat(buf," "); 19 } 20 printf("%s\n",buf); 21 return 0; 22 }