unix grep命令的大致实现

用到了strstr(a,b)函数和getline()函数,strstr(a,b)函数看是否能在字符串a中找到字符串b,若找到返回指向,若没找到返回NULL

strstr实现可以看:Implement strStr()

grep -xn 模式  ==>就是找出没有该模式的行并打印。

代码:

#include <stdio.h>
#include <string.h>
#define MAXLINE 1000
    
/*打印所有与第一个参数指定的模式相匹配的行*/
int main(int argc, char const *argv[])
{
    char line[MAXLINE];
    int c,found=0,except=0,number=0;
    int lineno=0;
    if(argc==1) return -1;

    while(--argc>0&& (*++argv)[0]=='-'){
        while(c=*++argv[0]){
            switch(c){
                case 'x':
                    except=1;
                    break;
                case 'n':
                    number=1;
                    break;
                default:
                    printf("Find:illegal option %c\n",c);
                    argc=0;
                    found=-1;
                    break;
            }
        }
    }

    while(found!=-1&&fgets(line,MAXLINE,stdin)>0){
        lineno++;
        if(except==1&&strstr(line,*argv)==NULL){
            if(number) 
                printf("%d:",lineno);
            printf("%s",line);
            found++;
        }
    }
    return found;
}

 

转载于:https://www.cnblogs.com/fightformylife/p/4348529.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值