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
",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