zoukankan      html  css  js  c++  java
  • popen

    popen
    在popen中调用下面的语句:
    df . | awk '{print $4}' | sed -n '2p'
    popen使用FIFO管道执行外部程序。
    #include <stdio.h>
    FILE *popen(const char *command, const char *type);
    int pclose(FILE *stream);
    popen 通过type是r还是w确定command的输入/输出方向,r和w是相对command的管道而言的。r表示command从管道中读入,w表示 command通过管道输出到它的stdout,popen返回FIFO管道的文件流指针。pclose则用于使用结束后关闭这个指针。
    下面看一个例子:
    /*******************************************************************************************
    ** Name:popen.c
    **      This program is used to show the usage of popen() .
    ** Author:zieckey,(zieckey@yahoo.com.cn)
    ** Date:2007/9/30 11:47
    ** All rights reserved!
    *******************************************************************************************/
    #include <sys/types.h>  
    #include <unistd.h>  
    #include <stdlib.h>  
    #include <stdio.h>  
    #include <string.h>
    int main( void )  
    {  
        FILE   *stream;  
        FILE    *wstream;
        char   buf[1024]; 
         
        memset( buf, '\0', sizeof(buf) );//初始化buf,以免后面写如乱码到文件中
        stream = popen( "ls -l", "r" ); //将“ls -l”命令的输出 通过管道读取(“r”参数)到FILE* stream
        wstream = fopen( "test_popen.txt", "w+"); //新建一个可写的文件
        fread( buf, sizeof(char), sizeof(buf),  stream);  //将刚刚FILE* stream的数据流读取到buf中
        fwrite( buf, 1, sizeof(buf), wstream );//将buf中的数据写到FILE    *wstream对应的流中,也是写到文件中
        
        pclose( stream );  
        fclose( wstream );
        
        return 0;
    }   
  • 相关阅读:
    [杂题]CSUOJ1274Balls and Boxes
    [Gauss]POJ1222 EXTENDED LIGHTS OUT
    [杂题]CSUOJ1413 Area of a Fractal
    [AC自动机]HDOJ3695 Computer Virus on Planet Pandora
    [dp]POJ2559 && HDOJ1506 Largest Rectangle in a Histogram
    [TSP+floyd]POJ3311 Hie with the Pie
    [状压dp]HDOJ3182 Hamburger Magi
    [状压dp]HDOJ1565 方格取数(1)
    [dp]Codeforces30C Shooting Gallery
    树套树模版
  • 原文地址:https://www.cnblogs.com/hbt19860104/p/2626638.html
Copyright © 2011-2022 走看看