i am unable to get the specific words. the task is to count the number of lines and specific words present in a text file. i was unable to count the specific words present in the text file. could anyone help me with it. Thanks in advance. my code:
#include <stdlib.h>
#include <ctype.h>
#include <string.h>
#include <stdio.h>
int main()
{
FILE *fp;
char filename[100];
char ch;
int linecount, wordcount,count;
linecount = 0;
wordcount = 0;
printf("Enter a filename :");
gets(filename);
fp = fopen(filename,"r");
if ( fp )
{
while ((ch=getc(fp)) != EOF) {
if (ch == ' ' || ch == '\n') { ++wordcount; }
if (ch == '\n') { ++linecount; }
}
if (wordcount > 0) {
++linecount;
++wordcount;
}
}
else
{
printf("failed to open the file\n");
}
printf("Lines : %d \n", linecount);
printf("Words : %d \n", wordcount);
#define MAX_WORD_LENGTH 10
char word[MAX_WORD_LENGTH + 1];
while ( getNextWord( word, sizeof word,fp ))
{
if ( match( word ) )
count++;
}
printf("total number of keywords %d",count);
return(0);
}
int getNextWord( char *target, size_t targetSize,FILE *fp )
{
size_t i = 0;
int c;
while ( (c = fgetc( fp )) != EOF && i < targetSize - 1 )
{
if ( isspace( c ) )
{
if ( i == 0 )
continue;
else
break;
}
else
{
target[i++] = c;
}
}
target[i] = 0;
return i > 0;
}
int match( const char *word )
{
const char *targets[] = {"the","two",""};
const char *t = targets;
while ( *t[0] != '\0' && strcmp(*t, word))
t++;
return t[0] != '\0';
}
the task is to count the number of lines and specific words present in a text file. i was unable to count the specific words present in the text file. could anyone help me with it. Thanks in advance.