Dummy commit to test new ssh key
[eleutheria.git] / homework / charfreq.c
blob276c568d23a32326b077e3f3a484e6a010bf5a5d
1 /*
2 * Compile with:
3 * gcc charfreq.c -o charfreq -Wall -W -Wextra -ansi -pedantic
4 */
6 #include <ctype.h>
7 #include <stdio.h>
8 #include <stdlib.h>
10 int main(int argc, char *argv[])
13 * When we partially initialize an array,
14 * C automatically initializes the rest of it
15 * to 0, NULL, etc, depending on the element type
16 * of the array.
17 * That said, the following is adequate:
19 unsigned int freq[26] = { 0 }; /* Frequencies for 'A' to 'Z' */
20 unsigned int i, j, len, maxf;
21 int c;
22 FILE *fp;
24 /* Check argument count */
25 if (argc != 2) {
26 fprintf(stderr, "Usage: %s path\n", argv[0]);
27 exit(EXIT_FAILURE);
30 /* Open file for reading */
31 if ((fp = fopen(argv[1], "r")) == NULL) {
32 perror("fopen");
33 exit(EXIT_FAILURE);
36 /* Count frequencies */
37 while ((c = fgetc(fp)) != EOF) {
38 c = toupper(c);
39 if (c >= 'A' && c <= 'Z')
40 freq[c - 'A']++;
43 /* Calculate size of array */
44 len = sizeof freq / sizeof *freq;
46 /* Get max frequency */
47 maxf = freq[0];
48 for (i = 1; i < len; i++)
49 if (freq[i] > maxf)
50 maxf = i;
52 /* Print frequencies */
53 i = maxf;
54 for (i = freq[maxf]; i > 0; i--) {
55 printf("%3u| ", i);
56 for (j = 0; j < len; j++)
57 if (freq[j] >= i)
58 printf("*");
59 else
60 printf(" ");
61 printf("\n");
64 /* Print letters */
65 printf(" ");
66 for (i = 0; i < len; i++)
67 printf("%c", (char)('A' + i));
68 printf("\n");
72 * Close file
73 * (since we opened the file only for read,
74 * we assume that it is safe to not check against
75 * the return value of fclose())
77 (void)fclose(fp);
79 return EXIT_SUCCESS;