#include #include #define MAXSTRLEN (81) #define MAXMARKS (60) char *reverse(char *a); char *stripCR(char *s); int main(int argc, char *argv[]) { char filename[MAXSTRLEN]; long int count[256]; int i, j; FILE *fp; long int max, bytes; int marks; double marksize; // Check for file name on command line, get from user if not found if(argc < 2) { printf("Enter filename: "); fgets(filename, MAXSTRLEN, stdin); stripCR(filename); } else { strncpy(filename, argv[1], MAXSTRLEN); } // Open file for reading (in binary mode) printf("Attempting to open file: <%s>\n", filename); fp = fopen(filename, "rb"); if(NULL == fp) { printf("Failed to open file for reading - abort!\n"); return(1); } // Initialize count variables for(i = 0; i < 256; i++) count[i] = 0; bytes = 0; // count values in file while(!feof(fp)) { count[fgetc(fp)]++; bytes++; } // Find most frequent value for(max = 0, i = 0; i < 256; i++) if(count[i] > max) max = count[i]; // determine the scale factor for the histogram bars marksize = (double) MAXMARKS / (double) max; // Output histogram for(i = 0; i < 256; i++) { printf("%03i: <% 8li> ", i, count[i]); marks = (int) (count[i] * marksize); for(j = 0; j < MAXMARKS; j++) printf("%c", (j < marks)? '*' : ' '); printf("\n"); } // Ouptut summary info printf("\nTotal bytes = %li\n", bytes); return(0); } char *stripCR(char *s) { char *a; a = s; do { switch(*a) { case '\n': case '\f': *a = '\0'; } } while('\0' != *(a++)); return(s); }