#include <stdio.h>
#include <ctype.h>
typedef struct CHAR_FREQUENCY_ANALYSIS_
{
size_t Frequency;
double Percentage;
unsigned char Character;
}CHAR_FREQ_ANAL;
int printCFA(CHAR_FREQ_ANAL *);
main(int argc, char *argv[])
{
FILE *data;
CHAR_FREQ_ANAL cfa[26] = {{0, 0, 0}};
size_t thisEntry;
size_t thisByte;
size_t fileLen;
char *prog = argv[0];
unsigned char alphabet[] = "abcdefghijklmnopqrstuvwxyz";
unsigned char ch;
size_t count = 0;
int pos;
/* file handling */
if(argc == 1)
{
fprintf(stderr, "ERROR: %s requires a target file.\n", prog);
exit(1);
}
else
{
if((data = fopen(*++argv, "r")) == NULL)
{
fprintf(stderr, "ERROR: %s cannot open file %s\n", prog, *argv);
exit(1);
}
}
/* find the file length */
fseek(data, 0L, SEEK_END);
fileLen = ftell(data);
fseek(data, 0L, SEEK_SET);
/* initialize the structure members */
for(thisEntry = 0; thisEntry < 26; thisEntry++)
{
cfa[thisEntry].Frequency = 0;
cfa[thisEntry].Percentage = 0.0;
cfa[thisEntry].Character = alphabet[thisEntry];
}
/* get a char and if its alphabetic update the struct */
for(thisByte = 0; thisByte < fileLen; thisByte++)
{
if(isalpha(ch = fgetc(data)))
{
pos = tolower(ch) - 'a';
++cfa[pos].Frequency;
++count;
}
}
/* run thru the array and calculate the Frequency */
for(thisEntry = 0; thisEntry < 26; thisEntry++)
{
cfa[thisEntry].Percentage = (double) cfa[thisEntry].Frequency * 100.0 / count;
}
/* Display the Results */
fprintf(stdout, "Character Frequency Analyzer by typedeaF @
www.osix.net\n\n");
printCFA(cfa);
exit(0);
}
int printCFA(CHAR_FREQ_ANAL *cfa)
{
size_t x;
printf("Ch Count %%age Ch Count %%age\n");
for(x = 0; x < 13; x++)
{
printf(" %c %9lu %6.3f %c %9lu %6.3f\n", cfa[x].Character, (unsigned long)cfa[x].Frequency, cfa[x].Percentage, cfa[x + 13].Character, (unsigned long)cfa[x + 13].Frequency, cfa[x + 13].Percentage);
}
return 0;
}