/* hist.c - display histogram of letters in input * Andrew Ho (andrew@zeuscat.com) * * Displays a human readable histogram of the distribution of letters * in the input text. Letters are normalized to lowercase. If no filename * is specified, tries to read /usr/dict/words. * * Build: gcc -lm -o hist hist.c * Usage: hist [filename] */ #include #include #include #include #define BUFSIZE 1024 #define COLUMNS 80 #define LETTERS 26 int main(int argc, char **argv) { FILE *fh; char buf[BUFSIZE], *fmt; int max, b, i, j; int hist[LETTERS]; for(i = 0; i < LETTERS; i++) hist[i] = 0; if(argc > 1) { fh = fopen(argv[1], "r"); } else { fprintf(stderr, "hist: opening default /usr/dict/words file\n"); fh = fopen("/usr/dict/words", "r"); } if(!fh) { perror("hist: could not open input"); return 1; } while( (b = fread(buf, sizeof(char), BUFSIZE, fh)) ) for(i = 0; i < b; i++) if(isalpha((unsigned char)buf[i])) hist[tolower(buf[i]) - 'a']++; fclose(fh); max = 0; for(i = 0; i < LETTERS; i++) if(max < hist[i]) max = hist[i]; fmt = (char *)malloc(COLUMNS * sizeof(char)); sprintf(fmt, "%%c %%%dd ", (int)(log(max) / log(10)) + 1); for(i = 0; i < LETTERS; i++) { fprintf(stdout, fmt, i + 'a', hist[i]); for(j = 0; j < hist[i] * (int)(COLUMNS * 0.8) / max; j++) fputs("*", stdout); fputs("\n", stdout); } return 0; }