Develop a C program that searches a le for a given string. Your program should •
ID: 3762047 • Letter: D
Question
Develop a C program that searches a le for a given string.
Your program should
• Ask the user to enter the le to be searched.
• Ask the user to enter the target string (string can be longer than one word, but no longer than a line)
• Locate the target string in the le.
NOTE: the target string may also be contained within the string read from the le.
Your program should be able to identify the target string as a part of another strings.
• Print the line number as well as the entire line where a match occurs
Explanation / Answer
COMMENTS ADDED
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
//method to search given word in a file
int Search_in_File(char *filename, char *str) {
//variables declaring
FILE *fp;
int line_number = 1;
int result = 0;
char temp[512];
//trying to opening a file
if((fp = fopen(filename, "r")) == NULL) {
return -1;
}
//processing through file
while(fgets(temp, 512, fp) != NULL) {
if((strstr(temp, str)) != NULL) {
printf("A match found on line number : %d ", line_number);
printf(" %s ", temp);
result++;
}
line_number++;
}
//if match is not found in file
if(result == 0) {
printf(" Not found in given file. ");
}
//closing file
if(fp) {
fclose(fp);
}
return(0);
}
//main starts here
int main() {
//variables declaring
int res, errno;
char filename[256];
char match[256];
//rading filename and string to match from user
printf("Enter filename: ");
fgets(filename, sizeof(filename), stdin);
printf(" Enter word to search: ");
fgets(match, sizeof(match), stdin);
//calling method
res = Search_File(filename,match);
//if file not found, filling errror number and status
if(res== -1) {
perror("Error");
printf("Error number = %d ", errno);
exit(1);
}
return 0;
}
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.