freq.c 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127
  1. /*
  2. * This file is part of the UCB release of Plan 9. It is subject to the license
  3. * terms in the LICENSE file found in the top-level directory of this
  4. * distribution and at http://akaros.cs.berkeley.edu/files/Plan9License. No
  5. * part of the UCB release of Plan 9, including this file, may be copied,
  6. * modified, propagated, or distributed except according to the terms contained
  7. * in the LICENSE file.
  8. */
  9. #include <u.h>
  10. #include <libc.h>
  11. #include <bio.h>
  12. uint64_t count[Runemax+1];
  13. Biobuf bout;
  14. void usage(void);
  15. void freq(int, char*);
  16. int32_t flag;
  17. enum
  18. {
  19. Fdec = 1<<0,
  20. Fhex = 1<<1,
  21. Foct = 1<<2,
  22. Fchar = 1<<3,
  23. Frune = 1<<4,
  24. };
  25. void
  26. main(int argc, char *argv[])
  27. {
  28. int f, i;
  29. flag = 0;
  30. Binit(&bout, 1, OWRITE);
  31. ARGBEGIN{
  32. case 'd':
  33. flag |= Fdec;
  34. break;
  35. case 'x':
  36. flag |= Fhex;
  37. break;
  38. case 'o':
  39. flag |= Foct;
  40. break;
  41. case 'c':
  42. flag |= Fchar;
  43. break;
  44. case 'r':
  45. flag |= Frune;
  46. break;
  47. default:
  48. usage();
  49. }ARGEND
  50. if((flag&(Fdec|Fhex|Foct|Fchar)) == 0)
  51. flag |= Fdec | Fhex | Foct | Fchar;
  52. if(argc < 1) {
  53. freq(0, "-");
  54. exits(0);
  55. }
  56. for(i=0; i<argc; i++) {
  57. f = open(argv[i], 0);
  58. if(f < 0) {
  59. fprint(2, "open %s: %r\n", argv[i]);
  60. continue;
  61. }
  62. freq(f, argv[i]);
  63. close(f);
  64. }
  65. exits(0);
  66. }
  67. void
  68. usage(void)
  69. {
  70. fprint(2, "usage: freq [-cdorx] [file ...]\n");
  71. exits("usage");
  72. }
  73. void
  74. freq(int f, char *s)
  75. {
  76. Biobuf bin;
  77. int32_t c, i;
  78. memset(count, 0, sizeof(count));
  79. Binit(&bin, f, OREAD);
  80. if(flag & Frune) {
  81. for(;;) {
  82. c = Bgetrune(&bin);
  83. if(c < 0)
  84. break;
  85. count[c]++;
  86. }
  87. } else {
  88. for(;;) {
  89. c = Bgetc(&bin);
  90. if(c < 0)
  91. break;
  92. count[c]++;
  93. }
  94. }
  95. Bterm(&bin);
  96. if(c != Beof)
  97. fprint(2, "freq: read error on %s\n", s);
  98. for(i=0; i<nelem(count); i++) {
  99. if(count[i] == 0)
  100. continue;
  101. if(flag & Fdec)
  102. Bprint(&bout, "%3ld ", i);
  103. if(flag & Foct)
  104. Bprint(&bout, "%.3lo ", i);
  105. if(flag & Fhex)
  106. Bprint(&bout, "%.2lx ", i);
  107. if(flag & Fchar) {
  108. if(i <= 0x20 ||
  109. (i >= 0x7f && i < 0xa0) ||
  110. (i > 0xff && !(flag & Frune)))
  111. Bprint(&bout, "- ");
  112. else
  113. Bprint(&bout, "%C ", (int)i);
  114. }
  115. Bprint(&bout, "%8llu\n", count[i]);
  116. }
  117. Bflush(&bout);
  118. }