#include<stdlib.h>
#include<stdio.h>

main(int argc, char *argv[]) {
  FILE *f; int stat[26],c,i;
  for(i=0;i<26;i++) stat[i]=0;
  if(argc!=2) { printf("usage: a.out file\n"); exit(1); }
  if(!(f=fopen(argv[1],"r"))) { printf("open in-file error!\n"); exit(1); }
  
  while(c!=EOF) {
    c=fgetc(f);
    if(isalpha(c)) { 
      if(islower(c)) c-=32;
      stat[c-65]++;
    }
  }
  for(i=0;i<26;i++) printf(">%c:%d\n",i+65,stat[i]);
  close(f);
 

  // Save stat to binary file. 
  if(!(f=fopen("out","wb"))) { printf("open bin-file error!\n"); exit(1); }
  printf("Wrote %d\n",fwrite(stat,sizeof(int),26,f));
  fflush(f); close(f);
  for(i=0;i<26;i++) stat[i]=0;

  // Read stat from binary file. 
  if(!(f=fopen("out","rb"))) { printf("open bin-file error!\n"); exit(1); }
  printf("Read %d\n",fread(stat,sizeof(int),26,f));
  close(f);

  // Test result and error check.
  for(i=0;i<26;i++) printf("<%c:%d\n",i+65,stat[i]);
  printf("Error: %d\n", ferror(f));
  printf("EOF: %d\n", feof(f));
}

