Skip to content

Instantly share code, notes, and snippets.

@tallpeak
Last active March 6, 2023 02:42
Show Gist options
  • Save tallpeak/698164d4beff24351cf599daf7cc3555 to your computer and use it in GitHub Desktop.
Save tallpeak/698164d4beff24351cf599daf7cc3555 to your computer and use it in GitHub Desktop.
Character frequency
#include <stdio.h>
#include <string.h>
//maybe works on posix not working for me on windows (S_ISCHR not defined)
//https://comp.os.os2.programmer.porting.narkive.com/s5n0plkf/how-to-set-stdin-stdout-stderr-to-binary-mode
// #include <io.h> // setmode()
// #include <fcntl.h> // O_BINARY
// #include <stdio.h> // FILE, fileno()
// #include <sys/stat.h> // struct stat, fstat(), S_ISCHR()
// static inline void set_bin_mode(FILE *stream)
// {
// struct stat st;
// fstat(fileno(stream), &st);
// if(!S_ISCHR(st.st_mode.))
// setmode(fileno(stream), O_BINARY);
// }
#define _O_BINARY 0x8000
int main(int argc, char **argv)
{
int c;
int freq[256];
memset((void*)freq, 0, sizeof(freq));
printf("Top hex digits are the second digit of the character value\nLeft-side hex numbers are the first digit of the character value\nnumbers in the table are the frequence of each character found in stdin.\n");
_setmode(_fileno(stdin),_O_BINARY);
//set_bin_mode(stdin);
while((c = getchar()) != EOF) {
freq[c]++;
}
//header: upper hex digits of the character value
printf(" ");
for (int h=0;h<16;h++){
printf("%6x ",h);
}
// header-separator lines
char *l = "=======";
printf("\n %s%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s",
l,l,l,l,l,l,l,l,l,l,l,l,l,l,l,l);
for (c=0;c<=255;c++) {
if (!(c & 0xf)) {
printf("\n%02x: ", c);
}
printf("%7d", freq[c]);
}
putchar('\n');
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment