+ 3

How to count specific words in a text file

i am unable to get the specific words. my code: ``` #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); } ``` 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.

3rd Nov 2019, 1:43 PM
jarvis
jarvis - avatar
2 Réponses
+ 5
How u wrote that function match inside of main, i think it should be maintained at outside, and u need to do some extra work there, when ever space or tab space or new line is encountered, upto that point what the characters u read i.e word should be compared using that match function
3rd Nov 2019, 2:04 PM
🐆 Janaki Ramudu 🅓🅞🅝 🇮🇳
🐆 Janaki Ramudu 🅓🅞🅝   🇮🇳 - avatar
+ 1
check this out: #include <stdlib.h> #include <ctype.h> #include <string.h> #include <stdio.h> int main() { FILE *fp; char filename[100]; char ch; int linecount, wordcount; 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); return(0); } int getNextWord( char *target, size_t targetSize, 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[] = {"and", "the", NULL}; const char *t = targets; while ( t && strcmp( t, word )) t++; return t != NULL; } #define MAX_WORD_LENGTH 10 char word[MAX_WORD_LENGTH + 1]; while ( getNextWord( word, sizeof word, fp )) { if ( match( word ) ) count++; } printf("%d",count);
4th Nov 2019, 1:53 PM
jarvis
jarvis - avatar