C Program to count number of occurrences of keywords in a file

C Program to count number of occurrences of keywords in a file

Mostly bloggers will be concentrating on the keyword density i.e, the no.of occurrences of a given word that is being more stressed in the post. So, I thought a C program might serve their need. The below program would find the frequency of a given set of strings in your post.

What made me to write this post?

When I was making a post, I was in need to know how many times I have used the keyword. To know about the frequency a good text editor might suit my need. But I'm a guy who don't want to use it unless I know how it works. So, I wrote a C program to count no.of occurrences of a given set of strings and simulate the function of the editor.
When I got this idea of how write the program, I thought that it was much lengthier and complex. I asked a friend of mine who said the same. So, naturally I didn't go to write it for a long time. But, I don't know what drove me to write it, got out from sleep at 4 am today morning and sat with a book of C programming. Actually I was not much familiar with files handling in C. When I was at the end of concept of Files, I was feeling it much simpler than what I thought.

The program goes like this...

Input: Set of strings.
Output: Frequency of each string in the file appended at the end of it.
Algorithm:
  1. Get the path of File
  2. Get the no.of keywords to be scanned for
  3. Store all the keywords in an array
  4. Set count to zero
  5. Search for every occurrence of string in the file using conventional string comparison
  6. Append it at the end of file
  7. if their exists another keyword to be searched for them go to to step 4
#include<stdio.h>
#include<string.h>
int main(int argc, char const *argv[])
{
 FILE *fp;
 char key[20][20],string[20],path[50];
 int count=0,n=0,i;
 printf("Enter the path of file");
 scanf("%s",path);
 printf("enter the no.of strings you want to search for");
 scanf("%d",&n);
 printf("Enter the set of strings(each in a new line)that you want to find frequencies of");
 for(i=0;i<n;i++)
  scanf("%s",key[i]);
 for(i=0;i<n;i++){
  count=0;
  fp=fopen(path,"r");
  while(fscanf(fp,"%s",string)==1){
   if(strcmp(key[i],string)==0) count++;
  }
  fclose(fp);
  fp=fopen(path,"a");
  fprintf(fp,"\n occurances of %s=%d",key[i],count);
  fclose(fp);
 }
 return 0;
}

Conclusion

Though this is a very small program, I wanted to share with my readers to show that nothing is so hard as one thinks it to be. Whether you think YOU CAN, or you think YOU CAN'T, you're right..


1 comment:

  1. while(fscanf(fp,"%s",string)==1){
    if(strcmp(key[i],string)==0) count++;
    }
    Cn u explain the meaning of these
    line of code

    ReplyDelete

Please DO NOT SPAM. You're not allowed to use links in comments unless it's necessary.

I Appreciate your valuable Feedback.

Regards,

www.TricksStar.com