Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

Problem We wish to create a utility that will search a text file for a specified

ID: 3605626 • Letter: P

Question

Problem We wish to create a utility that will search a text file for a specified string. Unix has a command line utility that does this called grep, which is a funny acronym that stands for globally search a regular expression and print. 1 (35 points): grep Write a C program that will search a text file for a specified string. Your program should a) Prompt the user for the name of the file to be searched. b) Prompt the user for the string to be found in the file. c) Print the name of the file searched. d) If the string is found then print the entire line of text where the string was found and the line number. e) Print the number of times the string was found. Assumptions for this assignment . Assume that all strings have a maximum length of 200 characters · Assume that each line of the file being searched is no more than 200 characters long. » Assume case sensitivitv. For example, if the file being searched contains OK and the string to find is ok then a match is not found; i.e. you do not need to worry about changing uppercase characters to lowercase or vice versa.

Explanation / Answer

#include <stdio.h>

#include <string.h>

int main(){

char fname[50];

printf("Enter the file name: ");

gets(fname);

FILE *fp;

fp = fopen(fname,"r");

char key[200];

printf("Enter in the search string: ");

gets(key);

int keylen;

keylen = strlen(key);

char buffer[200];

int wordcount=0,linecount=0;

while (fgets(buffer,200, fp) != NULL)

{

linecount++;

char *ret;

char temp[200];

ret = strstr(buffer,key);

if(ret != NULL){

printf("Found %s on line %d: %s ",key,linecount,buffer);

}

while( ret != NULL ){

wordcount++;

strcpy(temp,ret+keylen);

strcpy(buffer,temp);

ret = strstr(buffer,key);

}

}

printf("The string: "%s" was found a total of %d times in the file: %s ",key,wordcount,fname);

return 0;

}

Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
Chat Now And Get Quote