C++ Program to Implement Grep, Egrep and Fgrep Commands

This is a C++ Program to implement grep linux command.

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. {
  5.     char fn[10], pat[10], temp[200];
  6.     FILE *fp;
  7.     printf("\n Enter file name : ");
  8.     scanf("%s", fn);
  9.     printf("Enter the pattern: ");
  10.     scanf("%s", pat);
  11.     fp = fopen(fn, "r");
  12.     while (!feof(fp))
  13.     {
  14.         fgets(temp, sizeof(fp), fp);
  15.         if (strcmp(temp, pat))
  16.             printf("%s", temp);
  17.     }
  18.     fclose(fp);
  19.     return 1;
  20. }

Output:

$ g++ grep.cpp
$ a.out
 
Enter file name : prog.cpp
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;}}
 
------------------
(program exited with code: 0)
Press return to continue

Sanfoundry Global Education & Learning Series – 1000 C++ Programs.

advertisement
advertisement

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

If you find any mistake above, kindly email to [email protected]

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.