Reputation: 31
Program in C to count the frequency of a given word in a text file
I made this program with the purpose of counting the frequency of a given word in a text file, but in count the characters.
Need help to fix it.
#include <stdio.h>
#include <stdlib.h>
int main()
{
FILE * fptr;
char ch, * word, * a;
int i=0, p=0;
word =(char *) malloc(25 * sizeof(char));
fptr = fopen("text.txt", "r");
if (!fptr)
{
printf("File not found. \n");
}
else
{
printf("Word: ");
scanf("%s", word);
while(word[p]!='\0')
{
p++;
}
a=(char *) malloc(p * sizeof(char));
while (*(ch+a) != EOF)
{
*(ch+a) = getc(fptr);
if (*(ch+a) == * word)
{
i++;
}
}
}
if (i==0)
printf("Word not found.\n");
else
{
printf("Word found %d times.\n",i);
}
fclose(fptr);
return 0;
}
Upvotes: 1
Views: 2635
Reputation: 687
The bug in your code is that getc()
only get one character into memory. SO you must NOT make this *(ch+a) == * word
since ch
has a value not an address.
let ch='x'
and let a=10
so *(ch+a)==*('x'+10)
which would derefernce an address you didn't allocate.
This website implements countOccurancees
function, which take a pointer to const char
and a file pointer and return the number of word occurrences.
The strstr()
helps finding a first occurrence of a word by returning a pointer to the beginning of the located sub‐string.
#define BUFFER_SIZE 100
int countOccurrences(FILE *fptr, const char *word)
{
char str[BUFFER_SIZE];
char *pos;
int index, count;
count = 0;
// Read line from file till end of file.
while ((fgets(str, BUFFER_SIZE, fptr)) != NULL)
{
index = 0;
// Find next occurrence of word in str
while ((pos = strstr(str + index, word)) != NULL)
{
// Index of word in str is
// Memory address of pos - memory
// address of str.
index = (pos - str) + 1;
count++;
}
}
return count;
}
So in main
function just make i=countOccurrences(fptr, word);
main
should be look like
int main()
{
FILE * fptr;
char * word;
int i=0;
word = malloc(25 * sizeof(char));//Do NOT cast
fptr = fopen("text.txt", "r");
if (!fptr)
printf("File not found. \n");
else
{
printf("Word: ");
scanf("%s", word);
i=countOccurrences(fptr, word);
}
if (i==0)
printf("Word not found.\n");
else
printf("Word found %d times.\n",i);
fclose(fptr);
return 0;
}
Upvotes: 1