0% found this document useful (0 votes)
235 views

Simulation of Grep Command

This C program implements a basic grep function that searches a file for a given pattern. It takes the filename and pattern as command line arguments, opens the file, reads each line, and checks if the line contains the pattern using strstr. It prints out any matching lines along with the line number and increments a count of occurrences.

Uploaded by

Adri Jovin
Copyright
© Attribution Non-Commercial (BY-NC)
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
235 views

Simulation of Grep Command

This C program implements a basic grep function that searches a file for a given pattern. It takes the filename and pattern as command line arguments, opens the file, reads each line, and checks if the line contains the pattern using strstr. It prints out any matching lines along with the line number and increments a count of occurrences.

Uploaded by

Adri Jovin
Copyright
© Attribution Non-Commercial (BY-NC)
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 1

#include<stdio.

h>
#include<string.h>
#define max 1024
void usage()
{
printf("usage:\t./grep filename pattern \n");
printf("example: ./grep grep.c int\n");
}
int main(int argc,char *argv[])
{
FILE *fp;
char fline[max];
char *newline;
int count=0;
int occurences=0;
if(argc!=3)
{
usage();
exit(1);
}
if(!(fp=fopen(argv[1],"r")))
{
printf("grep : Couldnot open file : %s\n",argv[1]);
exit(1);
}
while(fgets(fline,max,fp)!=NULL)
{
count++;
if(newline=strchr(fline,'\n'))
*newline='\0';
if(strstr(fline,argv[2])!=NULL)
{
printf("%s: %d %s\n",argv[1],count,fline);
occurences++;
}
}
}

You might also like