]> git.lizzy.rs Git - plan9front.git/blob - sys/src/cmd/strings.c
ndb/dnsquery, ndb/csquery: handle long lines
[plan9front.git] / sys / src / cmd / strings.c
1 #include        <u.h>
2 #include        <libc.h>
3 #include        <bio.h>
4
5 Biobuf  fin;
6 Biobuf  fout;
7
8 void stringit(int);
9 int isprint(Rune);
10
11 int minspan = 6;        /* Min characters in string (default) */
12 Rune *span;
13
14 static void
15 usage(void)
16 {
17         fprint(2, "usage: %s [-m min] [file...]\n", argv0);
18         exits("usage");
19 }
20
21 void
22 main(int argc, char **argv)
23 {
24         int i, fd;
25
26         ARGBEGIN{
27         case 'm':
28                 minspan = atoi(EARGF(usage()));
29                 if(minspan <= 0)
30                         usage();
31                 break;
32         default:
33                 usage();
34                 break;
35         }ARGEND
36
37         span = malloc(sizeof(Rune)*(minspan+1));
38         if(span == nil)
39                 sysfatal("out of memory");
40
41         Binit(&fout, 1, OWRITE);
42         if(argc < 1) {
43                 stringit(0);
44                 exits(0);
45         }
46
47         for(i = 0; i < argc; i++) {
48                 if(argc > 1){
49                         Bprint(&fout, "%s:\n", argv[i]);
50                         Bflush(&fout);
51                 }
52                 if((fd = open(argv[i], OREAD)) < 0){
53                         perror("open");
54                         continue;
55                 }
56                 stringit(fd);
57                 close(fd);
58         }
59
60         exits(0);
61 }
62
63 void
64 stringit(int fd)
65 {
66         Rune *sp;
67         long c;
68
69         Binit(&fin, fd, OREAD);
70         sp = span;
71         while((c = Bgetrune(&fin)) >= 0) {
72                 if(isprint(c)) {
73                         if(sp == nil){
74                                 Bputrune(&fout, c);
75                                 continue;
76                         }
77                         *sp++ = c;
78                         if((sp-span) < minspan)
79                                 continue;
80                         *sp = 0;
81                         Bprint(&fout, "%8lld: %S", Boffset(&fin)-minspan, span);
82                         sp = nil;
83                 } else {
84                         if(sp == nil)
85                                 Bputrune(&fout, '\n');
86                         sp = span;
87                 }
88         }
89         if(sp == nil)
90                 Bputrune(&fout, '\n');
91         Bterm(&fin);
92 }
93
94 int
95 isprint(Rune r)
96 {
97         if (r != Runeerror)
98         if ((r >= ' ' && r < 0x7F) || r > 0xA0)
99                 return 1;
100         return 0;
101 }