1 /*strings.c - print the strings of printable characters in files.
2 *
3 * Copyright 2014 Kyung-su Kim <kaspyx@gmail.com>
4 * Copyright 2014 Kyungwan Han <asura321@gmail.com>
5 *
6 * No Standard
7 * TODO: utf8 strings
8 * TODO: posix -t
9
10 USE_STRINGS(NEWTOY(strings, "an#=4<1fo", TOYFLAG_USR|TOYFLAG_BIN))
11
12 config STRINGS
13 bool "strings"
14 default y
15 help
16 usage: strings [-fo] [-n LEN] [FILE...]
17
18 Display printable strings in a binary file
19
20 -f Precede strings with filenames
21 -n At least LEN characters form a string (default 4)
22 -o Precede strings with decimal offsets
23 */
24
25 #define FOR_strings
26 #include "toys.h"
27
GLOBALS(long num;)28 GLOBALS(
29 long num;
30 )
31
32 void do_strings(int fd, char *filename)
33 {
34 int nread, i, wlen = TT.num, count = 0;
35 off_t offset = 0;
36 char *string = xzalloc(wlen + 1);
37
38 for (;;) {
39 nread = read(fd, toybuf, sizeof(toybuf));
40 if (nread < 0) perror_msg("%s", filename);
41 if (nread < 1) break;
42 for (i = 0; i < nread; i++, offset++) {
43 if (((toybuf[i] >= 32) && (toybuf[i] <= 126)) || (toybuf[i] == '\t')) {
44 if (count == wlen) fputc(toybuf[i], stdout);
45 else {
46 string[count++] = toybuf[i];
47 if (count == wlen) {
48 if (toys.optflags & FLAG_f) printf("%s: ", filename);
49 if (toys.optflags & FLAG_o)
50 printf("%7lld ",(long long)(offset - wlen));
51 printf("%s", string);
52 }
53 }
54 } else {
55 if (count == wlen) xputc('\n');
56 count = 0;
57 }
58 }
59 }
60 xclose(fd);
61 free(string);
62 }
63
strings_main(void)64 void strings_main(void)
65 {
66 loopfiles(toys.optargs, do_strings);
67 }
68