Chinaunix首页 | 论坛 | 博客
  • 博客访问: 57827
  • 博文数量: 30
  • 博客积分: 10
  • 博客等级: 民兵
  • 技术积分: 301
  • 用 户 组: 普通用户
  • 注册时间: 2012-03-25 22:19
个人简介

技术成就一切

文章分类

全部博文(30)

文章存档

2019年(1)

2015年(3)

2014年(24)

2013年(2)

我的朋友

分类: C/C++

2015-08-18 14:41:44

Linux下通过C执行命令的时候,一般都是使用system()方法,但是该方法执行命令的返回值是-1或0,而有时候,我们需要得到执行命令的结果,可以使用管道实现。

输出到文件流的函数是 popen(),例如:

FILE *isr;

isr = popen( "ls -l", "r" );

ls -l 命令的输出通过管道读取(r 参数)到isr;

下面是演示例子:

/*************************************************************************
    > File Name: tShell.cpp
    > Author: WangWei
    > Mail: wangweitopic@126.com 
    > Created Time: 2015年08月17日 星期一 19时44分04秒
 ************************************************************************/


#include<iostream>
#include<sys/types.h>
#include<string.h>
#include<stdio.h>
using namespace std;
char *command_system( const char *command );
int main()
{
    char *result = command_system( "date");                                                                                                                             
    printf( "%s\n", result );
    return 0;   
}


char *command_system( const char *command )
{
    FILE *fpRead;
    char *result = ""; 
    char buf[ 1024 ];




    memset( buf, '\0', sizeof( buf ) );
    fpRead = popen( command, "r" );


    while( fgets( buf, 1024-1, fpRead ) != NULL )
        result = buf;


    if( fpRead != NULL )
        pclose( fpRead );




    return result;
}







阅读(1101) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~