C Program to Implement Grep, Egrep and Fgrep Commands

This is a C Program to implment gerp linux command. Grep is a command-line utility that searches a plain text that matches a regular expression.

Here is source code of the C Program to Implement the Program Used in grep/egrep/fgrep. The C program is successfully compiled and run on a Linux system. The program output is also shown below.

  1. #include<stdio.h>
  2. #include<dirent.h>
  3. int main() {
  4.     char fn[10], pat[10], temp[200];
  5.     FILE *fp;
  6.     printf("\n Enter file name : ");
  7.     scanf("%s", fn);
  8.     printf("Enter the pattern: ");
  9.     scanf("%s", pat);
  10.     fp = fopen(fn, "r");
  11.     while (!feof(fp)) {
  12.         fgets(temp, sizeof(fp), fp);
  13.         if (strcmp(temp, pat))
  14.             printf("%s", temp);
  15.     }
  16.     fclose(fp);
  17.     return 1;
  18. }

Output:

$ gcc grep.c
$ ./a.out
 
Enter file name : program.c
Enter the pattern: while
 
#include<stdio.h>#include<dirent.h>int main() {    char fn[10], pat[10], temp[200];    FILE *fp;    printf("\n Enter file name : ");    scanf("%s", fn);    printf("Enter the pattern: ");    scanf("%s", pat);    fp = fopen(fn, "r");    while (!feof(fp)) {        fgets(temp, sizeof(fp), fp);        if (strcmp(temp, pat))            printf("%s", temp);    }    fclose(fp);    return 1;}}

Sanfoundry Global Education & Learning Series – 1000 C Programs.

advertisement

Here’s the list of Best Books in C Programming, Data Structures and Algorithms.

advertisement
advertisement
Subscribe to our Newsletters (Subject-wise). Participate in the Sanfoundry Certification contest to get free Certificate of Merit. Join our social networks below and stay updated with latest contests, videos, internships and jobs!

Youtube | Telegram | LinkedIn | Instagram | Facebook | Twitter | Pinterest
Manish Bhojasia - Founder & CTO at Sanfoundry
I’m Manish - Founder and CTO at Sanfoundry. I’ve been working in tech for over 25 years, with deep focus on Linux kernel, SAN technologies, Advanced C, Full Stack and Scalable website designs.

You can connect with me on LinkedIn, watch my Youtube Masterclasses, or join my Telegram tech discussions.

If you’re in your 40s–60s and exploring new directions in your career, I also offer mentoring. Learn more here.