strings.c 1.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104
  1. #include <u.h>
  2. #include <libc.h>
  3. #include <bio.h>
  4. Biobuf *fin;
  5. Biobuf fout;
  6. #define MINSPAN 6 /* Min characters in string (default) */
  7. #define BUFSIZE 70
  8. void stringit(char *);
  9. int isprint(Rune);
  10. static int minspan = MINSPAN;
  11. static void
  12. usage(void)
  13. {
  14. fprint(2, "usage: %s [-m min] [file...]\n", argv0);
  15. exits("usage");
  16. }
  17. void
  18. main(int argc, char **argv)
  19. {
  20. int i;
  21. ARGBEGIN{
  22. case 'm':
  23. minspan = atoi(EARGF(usage()));
  24. break;
  25. default:
  26. usage();
  27. break;
  28. }ARGEND
  29. Binit(&fout, 1, OWRITE);
  30. if(argc < 1) {
  31. stringit("/fd/0");
  32. exits(0);
  33. }
  34. for(i = 0; i < argc; i++) {
  35. if(argc > 2)
  36. print("%s:\n", argv[i]);
  37. stringit(argv[i]);
  38. }
  39. exits(0);
  40. }
  41. void
  42. stringit(char *str)
  43. {
  44. long posn, start;
  45. int cnt = 0;
  46. long c;
  47. Rune buf[BUFSIZE];
  48. if ((fin = Bopen(str, OREAD)) == 0) {
  49. perror("open");
  50. return;
  51. }
  52. start = 0;
  53. posn = Boffset(fin);
  54. while((c = Bgetrune(fin)) >= 0) {
  55. if(isprint(c)) {
  56. if(start == 0)
  57. start = posn;
  58. buf[cnt++] = c;
  59. if(cnt == BUFSIZE-1) {
  60. buf[cnt] = 0;
  61. Bprint(&fout, "%8ld: %S ...\n", start, buf);
  62. start = 0;
  63. cnt = 0;
  64. }
  65. } else {
  66. if(cnt >= minspan) {
  67. buf[cnt] = 0;
  68. Bprint(&fout, "%8ld: %S\n", start, buf);
  69. }
  70. start = 0;
  71. cnt = 0;
  72. }
  73. posn = Boffset(fin);
  74. }
  75. if(cnt >= minspan){
  76. buf[cnt] = 0;
  77. Bprint(&fout, "%8ld: %S\n", start, buf);
  78. }
  79. Bterm(fin);
  80. }
  81. int
  82. isprint(Rune r)
  83. {
  84. if (r != Runeerror)
  85. if ((r >= ' ' && r < 0x7F) || r > 0xA0)
  86. return 1;
  87. return 0;
  88. }