Don't forget to release ps object in loop
[eleutheria.git] / homework / charfreq.c
blob1f010006456f4ff9d2ef28edd46d99f61ef1b185
1 #include <ctype.h>
2 #include <stdio.h>
3 #include <stdlib.h>
5 int main(int argc, char *argv[])
7 /*
8 * When we partially initialize an array,
9 * C automatically initializes the rest of it
10 * to 0, NULL, etc, depending on the element type
11 * of the array.
12 * That said, the following is adequate:
14 unsigned int freq[26] = { 0 }; /* Frequencies for 'A' to 'Z' */
15 unsigned int i, j, maxf;
16 int c;
17 FILE *fp;
19 /* Check argument count */
20 if (argc != 2) {
21 fprintf(stderr, "usage: %s path\n", argv[0]);
22 exit(EXIT_FAILURE);
25 /* Open file for reading */
26 if ((fp = fopen(argv[1], "r")) == NULL) {
27 perror("fopen");
28 exit(EXIT_FAILURE);
31 /* Count frequencies */
32 while ((c = fgetc(fp)) != EOF) {
33 c = toupper(c);
34 if (c >= 'A' && c <= 'Z')
35 freq[c - 'A']++;
38 /* Get max frequency */
39 maxf = freq[0];
40 for (i = 1; i < sizeof freq / sizeof *freq; i++)
41 if (freq[i] > maxf)
42 maxf = i;
44 /* Print frequencies */
45 i = maxf;
46 for (i = freq[maxf]; i > 0; i--) {
47 printf("%3u| ", i);
48 for (j = 0; j < sizeof freq / sizeof *freq; j++)
49 if (freq[j] >= i)
50 printf("*");
51 else
52 printf(" ");
53 printf("\n");
56 /* Print letters */
57 printf(" ");
58 for (i = 0; i < sizeof freq / sizeof *freq; i++)
59 printf("%c", (char)('A' + i));
60 printf("\n");
64 * Close file
65 * (since we opened the file only for read,
66 * we assume that it is safe to not check against
67 * the return value of fclose())
69 (void)fclose(fp);
71 return EXIT_SUCCESS;