popen() 的应用

#include<stdio.h>
FLIE * fp = popen(“ls -l”,“r”);失败为空,只要是指针的类型,返回值均为空,只要是判断的函数,失败为0,成功为1;
fread(buf , sizeof(char),sizeof(buf),fp); 把结果定向到 buf 里面
popen() 与exec 族函数不同的是,popen()还是要转回来 执行自己的函数

// add.c 
#include <stdio.h>

int main()

{
    int i , j; 
    scanf("%d%d",&i ,&j);

    printf("sum = %d\n",i+j);
    return 0;
}
//p.c
#include <stdio.h>

int main()
{
    int i, j;
    printf("Hello world\n");
    return 0;
}
// popen_w.c
#include <stdio.h>
#include<stdlib.h>
#include<unistd.h>
int main()
{
    FILE * fp = popen("./add", "w");
    if ( fp ==NULL )
    {
        printf("popen is wrong \n");
    }
    char buf[128]="3 4";
    fwrite(buf,sizeof(char),sizeof(buf),fp);  // 将buf 的内容餐位参数,写入 add.c的参数中
    pclose(fp);
    FILE *fp2 = popen("./p","r");
    fread(buf,sizeof(char),sizeof(buf),fp2);  //将输出到屏幕上的内容输出到buf里面
    printf("buf = %s",buf);
    printf("popen_w.c is over\n");
    pclose(fp2);
}
int main()
{
    FILE * fp = popen ( "ls -l","r"); // 将命令行的命令写入到 buf中
//  FILE * fp = popen("ls", "r");
    if ( fp ==NULL )
    {
        printf("popen is wrong \n");
    }
    char buf[128]={0};
    int ret= fread(buf,sizeof(char), sizeof(buf), fp);
    if( ret == -1 )
    {
        printf("fread is wrong \n");
    }
    printf("buf[127]=%c\n",buf[127]);
    printf("buf= %s\n",buf);
    
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值