Counting Number Of specific Word In A File

January 25, 2011 at 18:45:13
Specs: Windows XP
Hi,
I have one file, I need to read that file and count no of times repeated specific word.

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

main()
{
char text2[30];
int count=0;
char line [50];
//char *ret;
//static const char filename[] = "file.txt";
FILE *file = fopen("file.txt", "r" );
if( file != NULL )
{
while((fgets(line, sizeof(line), file))!= NULL)
{
strcpy(text2,line);
char* ret= strstr(text2, "SUCCESSFULLY");
if(ret!=NULL)
{
count++;
}

fclose ( file );
}
}
else
{
//perror ( filename );
fputs("There was an error reading the file.\n", stderr);
}
return 0;
getch();
}

In this program where it is wrong not understanding. could u please resolve.


See More: Counting Number Of specific Word In A File

Report •


#1
January 25, 2011 at 19:57:09
What you might try is using fscanf instead, convert the case of each word, and then test it.

while((fscanf(file, "%s", line)) == 1) {
   int i;
   for(i=0; (line[i] = toupper(line[i])) != '\0'; ++i){}
   if(strstr(line, "SUCCESSFULLY") != NULL)
      ++count;
}

HTH


Report •
Related Solutions


Ask Question