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

C Program question: Write a program that counts the number of occurrences of a s

ID: 3817746 • Letter: C

Question

C Program question:

Write a program that counts the number of occurrences of a substring within a file. The program must allow the user to enter both the substring the user wants to search for and the name of the file to be searched. The output message must include the number of occurrences of the substring, the substring, and the name of the file searched.

This is not an array problem. It is a file and string problem. It is not possible to store all the strings read from the file in some huge two-dimensional array. The file will likely contain too many strings for this.

For example, the program should run like this:

Enter the string that you want to search for:

the

Enter the name of the file you want to search through:

helpme.txt

There were 42 occurrences of the string "the" within the file helpme.txt.

How can one do this?

Explanation / Answer

#include<stdio.h>

#include<stdlib.h>

#include<string.h>

int main()

{

char string[20], file_name[25]; //declaring variables

int number_of_occurrences = 0;

char buffer[20];

FILE *file_pointer; //declaring a file pointer

printf("enter the string that you want to search for");

scanf("%s",string[20]); //entering substring

printf("enter the file name in which you want to search through");

scanf("%s",file_name[25]); //entering file name

if((file_pointer = fopen(file_name,"r")) != NULL) //checking for valid file address

{

while(fgets(buffer,20,file_pointer) != NULL) //reading string from file

{

if((strstr(buffer,string)) !=NULL) //checking for substring within the string reading from file

{

number_of_occurrences++; //counting number of occurrences

}

}

}

printf("the number of occurrences in file %s are %d",file_name[25],number_of_occurrences); //printing results

fclose(file_name); //closing file

}