码迷,mamicode.com
首页 > 其他好文 > 详细

实现grep命令

时间:2017-09-24 02:34:23      阅读:154      评论:0      收藏:0      [点我收藏+]

标签:name   nbsp   地址   strlen   logs   pre   err   搜索   fgets   

#include <stdio.h>
#include <string.h>
#include <stdlib.h>

// grep命令:grep match_pattern file_name
// 在file_name中搜索包含match_pattern的行
// ./a.out math  math
// 在math中搜索math所在的行
int main(int argc, char *argv[])
{
    FILE *fp = NULL;
    char buf[128], tmp[128];
    char *p = NULL;
    int count = 0;
    char *s = NULL;

    fp = fopen(argv[2], "r");
    if (NULL == fp)
    {
        perror("fopen");
        return -1;
    }

    //fgets:从文件中每次读取一行数据入buf 失败或者读到结尾返回NULL
    //file中的每行第buffsize个字符赋‘\0‘
    while (fgets(buf, sizeof(buf)-1, fp) != NULL)
    {
        //统计行
        count++;
        if ((p = strstr(buf, argv[1])) != NULL)
        {
            printf("%d :", count);
        }
        //打印匹配的字符窗
        s = buf;
        //p指向argv[1]第一次出现在s中的地址
        while((p = strstr(s, argv[1])) != NULL)
        {
            #if 1
            bzero(tmp, sizeof(tmp));
            memset(tmp, 0, sizeof(tmp));  //表示清空空间
            strncpy(tmp, s, p - s); //拷贝数据到临时空间中
            #else
            snprintf(tmp, p - s + 1, "%s", s);
            #endif
            printf("%s", tmp);
            printf("\033[31m%s\033[0m", argv[1]);
            s = p + strlen(argv[1]);
        }
        if (s != buf)
            printf("%s", s);
        
        /*sleep(1);*/
    }
    fclose(fp);
    return 0;
}

 

实现grep命令

标签:name   nbsp   地址   strlen   logs   pre   err   搜索   fgets   

原文地址:http://www.cnblogs.com/linuxAndMcu/p/7583577.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!