Last active
January 8, 2025 22:56
-
-
Save xorgy/fee5779d597bf542aa1cd3b83f7a3b03 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#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