---
title: "Linux下popen的使用"
author: "pipal"
date: "2011-01-15T23:16:39Z"
tags: []
categories: ["编程语言"]
slug: "linux-popen"
draft: false
lastmod: "2011-01-15T23:18:34Z"
id: 875498
url: "https://pipal.iteye.com/blog/875498"
---

C语言里有个popen函数，用来捕获shell里命令的输出，这样C和shell也可以相互通信了。在网上看了个例子修改了一下，原文：[http://blogold.chinaunix.net/u/16292/showart\_393022.html](http://blogold.chinaunix.net/u/16292/showart_393022.html)

 

```
/*

作用：演示popen用法，将源程序输出到argv[1]命名的文件中

使用：argv[0] outputFile

*/

#include <sys/types.h>  
#include <unistd.h>  
#include <stdlib.h>  
#include <stdio.h>  
#include <string.h>

#define CMDLEN  1024

int main(int argc, char** argv)  
{  
    do
    {
      if ( 2 != argc)
      {
        printf("Usage:%s outputFile!\n",argv[0]);
        break;
      }
      
      FILE   *stream;  
      FILE    *wstream;
      char   buf[1024]; 
      char   myCmd[CMDLEN];
      memset(myCmd,0,CMDLEN); 
      strcpy(myCmd,"cat ");
      strcat(myCmd,argv[0]);
      strcat(myCmd,".c");
      memset( buf, '\0', sizeof(buf) );//初始化buf,以免后面写如乱码到文件中
      stream = popen( myCmd, "r" ); //将myCmd命令的输出 通过管道读取（“r”参数）到FILE* stream
      wstream = fopen( argv[1], "w+"); //新建一个可写的文件

      fread( buf, sizeof(char), sizeof(buf),  stream);  //将刚刚FILE* stream的数据流读取到buf中
      fwrite( buf, 1, sizeof(buf), wstream );//将buf中的数据写到FILE    *wstream对应的流中，也是写到文件中
      
      pclose( stream );  
      fclose( wstream );
    }while(0);
    return 0;
}   

 
```