Skip to content

Instantly share code, notes, and snippets.

@xorgy
Last active April 21, 2017 03:19
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save xorgy/fee5779d597bf542aa1cd3b83f7a3b03 to your computer and use it in GitHub Desktop.
Save xorgy/fee5779d597bf542aa1cd3b83f7a3b03 to your computer and use it in GitHub Desktop.
#include <stdio.h>
#include <stdlib.h>
#include <strings.h>
#define BUFSIZE (1023 * 1024 * 4)
#define HISTSIZE (0x7f - ' ')
typedef struct hist_entry_s {
uint64_t count;
char codepoint;
} hist_entry;
int32_t fold_case = 0;
int32_t sort_direction = 1;
int32_t do_sort = 1;
int32_t print_empty_sets = 0;
int32_t compare_hist_entry(hist_entry * a, hist_entry * b) {
uint64_t ac = a->count;
uint64_t bc = b->count;
return (ac == bc ? 0 : ac < bc ? -1 : 1) * sort_direction * do_sort;
}
int32_t main(int argc, char * argv[]) {
size_t r;
char buf[BUFSIZE];
hist_entry h[HISTSIZE];
int32_t i;
for(i = 0; i < argc; i++) {
size_t l = strlen(argv[i]);
if(l > 1 && argv[i][0] == '-')
while(--l)
switch (argv[i][l]) {
case 'c':
fold_case = 1;
break;
case 'r':
sort_direction = -1;
break;
case 'n':
do_sort = 0;
break;
case 'e':
print_empty_sets = 1;
break;
}
}
for(i = ' '; i < 0x7f; i++)
h[i - ' '].codepoint = i;
while((r = fread((void *) buf, 1, BUFSIZE, stdin)))
while (r--) {
char v = buf[r];
if(v >= ' ' && v < 0x7f) {
if(fold_case && (v >= 'A' && v <= 'Z')) v += 32;
h[v - ' '].count++;
}
}
if (ferror(stdin)) {
fprintf(stderr, "Something went horribly wrong with reading stdin.");
exit(1);
}
qsort(h, HISTSIZE, sizeof(hist_entry),
(int (*)(const void *, const void *))compare_hist_entry);
for (i = 0; i < HISTSIZE; i++)
if (print_empty_sets || h[i].count != 0)
printf(" %c : %llu\n", h[i].codepoint, h[i].count);
exit(0);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment