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
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
Manish Bhojasia, a technology veteran with 20+ years @ Cisco & Wipro, is Founder and CTO at Sanfoundry. He lives in Bangalore, and focuses on development of Linux Kernel, SAN Technologies, Advanced C, Data Structures & Alogrithms. Stay connected with him at LinkedIn.

Subscribe to his free Masterclasses at Youtube & discussions at Telegram SanfoundryClasses.