summaryrefslogtreecommitdiff
path: root/reference/C/CONTRIB/SNIP/stats.c
blob: c17f8d6a0405004f248c8675977361168291c640 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
/****************************************************************/
/*                                                              */
/*      Collect file statistics                                 */
/*                                                              */
/*      Public domain demo program for analyzing encrypted      */
/*      files. By: Bob Stout                                    */
/*                                                              */
/****************************************************************/

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

main(int argc, char *argv[])
{
      int i, ch, hist = 0;
      long n = 0L;
      double mean = 0., stdev = 0., ftmp;
      static unsigned bins[256];
      FILE *infile;

      assert(infile = fopen(argv[1], "rb"));
      while (!feof(infile))
      {
            if (EOF == (ch = fgetc(infile)))
                  break;
            bins[ch] += 1;
            ++n;
      }
      fclose(infile);
      for (i = 0; i < 256; ++i)
      {
            mean += (double)(bins[i]);
            if (bins[i])
                  ++hist;
      }
      mean /= 256.;
      for (i = 0; i < 256; ++i)
      {
            ftmp = (double)(bins[i]) - mean;
            stdev += (ftmp * ftmp);
      }
      ftmp  = stdev / 255.;
      stdev = sqrt(ftmp);
      printf("%ld Characters were read from %s\n"
            "There are an average of %f occurances of each character\n"
            "%d Characters out of 256 possible were used\n"
            "The standard deviation is %f\n"
            "The coefficient of variation is %f%%\n",
            n, argv[1], mean, hist, stdev, (100. * stdev) / mean);
      return EXIT_SUCCESS;
}