Frequency of a string in a C file
This C program counts the number of occurrences in a text file of all the characters searched.Example:
Text file contains the text "I'm a programmer".
Characters you are looking for: j, s, p, e.
The number of occurrences:
j : 1
s: 1
u: 3
E: 2
#include < stdio.h>
#include < stdlib.h>
void rech_caracteres(char characters[],int size)
{
//open file in read mode
FILE *file = fopen("C:/test.txt","r");
char c;
//array that saves repeats
int repeat[size];
//initialize to 0
for(int i = 0 ; i < size; i++)
repeat[i]=0;
//if the file exists
if(file)
{
//as long as it's not the end of the file
//read a character
while((c=(char)getc(file))!=EOF)
{
//The read character is compare with
//all characters searched
for(int i = 0 ; i < size; i++)
{
//if equal, increment
//the counter associated with the character
if(c==characters[i])
repeat[i]++;
}
}
//close file
fclose(file);
//display
printf("Number of repetitions:\n");
for(int i = 0 ; i < size; i++)
printf("\t%c : %d\n",characters[i],repeat[i]);
}
else
printf("\aERROR: Unable to open file: %s", file);
}
int main()
{
char string[]="a programmer";
// sizeof(string)-1: size of the array
// (-1 to not count the '\0')
// '\0' indicates the end of the array
rech_caracteres(string,sizeof(string)-1);
system("pause");
}