Click here to Skip to main content
14,696,589 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
the number of lines and specific words present in a text file have to be counted. i was not able to count the specific words present in the text file. could anyone help me with it. Thanks in advance.

What I have tried:

#include <stdio.h>
#include <string.h>

int main()
{
 FILE *fp;
 char filename[100];
 char ch;
 int linecount;

 linecount = 0;

  printf("Enter a filename :");
  gets(filename);

   fp = fopen(filename,"r");

   int match( char *word )
{
  char *targets[] = {"auto", "the", ""};
  char **t = targets;

  while ( *t[0] != '\0' && strcmp(*t, word))
    t++;

  return *t[0] != '\0';
}


   if ( fp )
   {
       while ((ch=getc(fp)) != EOF) {

      if (ch == '\n') { ++linecount; }

       }

       if (linecount > 0) {
        ++linecount;
       }
    }
   else
      {
         printf("failed to open the file\n");
      }

    printf("Lines : %d \n", linecount);

return(0);
}
Posted
Updated 3-Nov-19 21:10pm
v3
Comments
Rick York 3-Nov-19 15:57pm
   
Do you have a definition of what constitutes a word? Typically there are delimiters that define the boundaries for a word. They would be things like whitespace and punctuation characters. Given you have delimiters defined, you might find the strtok function to be useful. I have.
Maciej Los 4-Nov-19 2:39am
   
My virtual 5!

Quote:
How do I count specific words in a text file

Hi Jarvis/Samuel you have already posted essentially the same question with another account, it tend to upset helpers here.
How do I count lines, words and keywords in a text file[^]
Your main change is removing the general words counting as it was wrong.

Hint:
Your problem is that you can't count words just with 1 char at the time.
You need to remember what was the previous char.
You have a new word when last read char is part of a word and previous char is not part of a word.
You also need to define which char is part of a word.

To count specific words:
you first need a list of those words.
then you need a way to detect beginning of general words, which is essentially the previous task.
then you need a pointer to know where you are in the list of specific words.
Advice: start by detecting a single specific word, then elaborate.

Advice: reading a full line in a buffer may simplify the code.
   
v2
The solution is very easy by scanning the file for words and store each entry in an array which also does the counting. If you you structs it would also look fine.
struct wordCounter {
  int count = 0;
  char *word;
}
Take care of memory allocation and freeing with alloc(), realloc() and free(). You need to alloc and the word memory too and store the size of the word array.
   

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)




CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900