让程序感知从管道输入

来源:互联网 发布:盐城平面软件培训 编辑:程序博客网 时间:2024/04/30 21:42
------------------------------------------------------------
author: hjjdebug
date:   Fri Jun 13 11:14:34 CST 2014
------------------------------------------------------------
让程序感知从管道输入:
通常,程序从文件输入,但是我们知道,grep sed awk 都可以即从文件输入
也可以接受管道输入, 就是从stdin 输入, 怎样让自己的程序也支持这种特性呢?

方法是: 当命令行中无参数时,就把stdin 作为读入文件描述符,经测试无误。
------------------------------------------------------------
附上我的测试结果。
------------------------------------------------------------
[hjj@hjj ~/ctest]$ echo "hello" | ./test
hello

[hjj@hjj ~/ctest]$ cat Makefile |./test
all:
    gcc -o test -g test.c
clean:
    rm test

[hjj@hjj ~/ctest]$ ./test Makefile
all:
    gcc -o test -g test.c
clean:
    rm test

------------------------------------------------------------
附上我的测试代码。
------------------------------------------------------------
[hjj@hjj ~/ctest]$ cat test.c
#include <stdio.h>
#include <stdlib.h>

int main(int argc, char *argv[])
{
    char buffer[256];
    FILE *fp=NULL;

    if(argc < 2)
    {
        fp=stdin;
    }
    if(fp==NULL)
    {
        fp=fopen(argv[1],"r");
        if(!fp)
        {
            perror("Err Reason:");
            exit(2);
        }
    }
    while(!feof(fp))
    {
        char *s=fgets(buffer,sizeof(buffer),fp);
        if(s) printf("%s",s);
    }
//    printf("ok\n");
    return 0;
}

0 0
原创粉丝点击