In this task, you will implement a simplified version of the grep program in C,
ID: 3739816 • Letter: I
Question
In this task, you will implement a simplified version of the grep program in C, called filegrep . The usage syntax of filegrep will be as follows filegrep PATTERN FILE Both command-line arguments are necessary. PATTERN is a string of characters. FILE is a name of a file in which search is performed. Note that, unlike grep, filegrep searches for the pattern literally as it is. In other words, you do not need to consider meta characters and regular expressions. Our test cases will only include patterns that contain alphanumeric characters The output of running the program using the above arguments must be exactly the same as running grep -n PATTERN FILE Note that the output should include line numbers. If less/more than two arguments are provided you must print the following message to stderr Usage: filegrep PATTERN FILE Moreover, if FILE is invalid, your program should print the same error that grep would print to stderr.Explanation / Answer
#include<stdio.h>
#include<string.h>
#include<stdlib.h>
void upper_string(char s[]);
int main(int argc, char **argv)
{
FILE *fp;
char line[100],lineu[100];
int count=0;
if(argc != 3){
fprintf(stderr, "Usage: filegrep pattern File ");
exit(1);
}
fp = fopen(argv[2],"r");
if(!fp){
fprintf(stderr, "filegrep: %s: No such file or directory ",argv[2]);
exit(1);
}
upper_string(argv[1]);
while(fscanf(fp , "%[^ ] " , line)!=EOF)
{
count++;
strcpy(lineu,line);
upper_string(lineu);
if(strstr(lineu , argv[1]) !=NULL)
{
printf("%d:%s " ,count, line);
}
else
{
continue;
}
}
fclose(fp);
return 0;
}
void upper_string(char s[]) {
int c = 0;
while (s[c] != '') {
if (s[c] >= 'a' && s[c] <= 'z') {
s[c] = s[c] - 32;
}
c++;
}
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.