Hi. I just wrote this program that's supposed to read from a file, count the frequency of each character, sort them, then output any characters in a file along with their frequencies:
Code:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define FILEPATH_MAX FILENAME_MAX*15
int main(int argc, char * argv[])
{
char filePath[FILEPATH_MAX];
FILE *file;
int i, k, maxchar;
char charcount[256] = {0}; /* array to know how many of a specific character have been seen */
char charcount2[256] = {0}; /* for sorting */
char charcount2_identifiers[256] = {0}; /* for sorting (identifiers for characters in charcount2 */
if (argc == 2)
strcpy(filePath, argv[1]);
else
{
fputs("Wrong arguments. Press enter to terminate...", stderr);
getchar();
exit(EXIT_FAILURE);
}
if ((file = fopen(filePath, "rt")) == '\0')
{
fputs("Error opening file. Press enter to terminate...", stderr);
getchar();
exit(EXIT_FAILURE);
}
printf("File opened successfully\n");
/* start counting */
while ((i=fgetc(file)) != EOF)
++charcount[i];
fclose(file);
/* sort */
for (i=0; i<256; i++)
{
for (k=0, maxchar=0; k<256; k++)
if (charcount[k] > maxchar)
{
maxchar = charcount[k];
charcount[k] = 0;
charcount2_identifiers[i] = k;
}
charcount2[i] = maxchar;
}
/* output results */
for (i=0; i<256; i++)
{
if (charcount2[i] != 0)
{
if (charcount2_identifiers[i] >= 33 && charcount2_identifiers[i] <= 126)
printf("%c: %d\n", charcount2_identifiers[i], charcount2[i]); /* print the identifier */
else
printf("0x%x: %d\n", charcount2_identifiers[i], charcount2[i]);
}
}
printf("Finished. Press enter to continue...");
getchar();
return 0;
}
The problem is, not all the characters in the file are output.
E.g. I tried the following text in a file:
UJTUQJ FQQ FWTZSI YMJ BTWQI QNPJ YT XTQAJ UZEEQJX
when I run the program it does not display the letter J or its frequencey.
I think the problem is in the sorting. I'm pretty sure the output part is right.
Thanks,