aboutsummaryrefslogtreecommitdiff
path: root/toys/pending/strings.c
blob: 1b53d8df103a54c520accdb2b25a3caacce9fe61 (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
54
55
56
57
58
59
60
61
62
63
64
65
66
/*strings.c - print the strings of printable characters in files.
 *
 * Copyright 2014 Kyung-su Kim <kaspyx@gmail.com>
 * Copyright 2014 Kyungwan Han <asura321@gmail.com>
 *
 * No Standard

USE_STRINGS(NEWTOY(strings, "n#=4<1fo", TOYFLAG_USR|TOYFLAG_BIN))

config STRINGS
  bool "strings"
  default n
  help
    usage: strings [-fo] [-n count] [FILE] ...

    Display printable strings in a binary file

    -f Precede strings with filenames
    -n [LEN] At least LEN characters form a string (default 4)
    -o Precede strings with decimal offsets
*/
#define FOR_strings
#include "toys.h"

GLOBALS(
  long num;
)

void do_strings(int fd, char *filename)
{
  int nread, i, wlen, count = 0;
  off_t offset = 0;
  char *string;

  string = xzalloc(TT.num + 1);
  wlen = TT.num - 1;

  while ((nread = read(fd,toybuf,sizeof(toybuf)))>0 ) {
    for (i = 0; i < nread; i++, offset++) {
      if (((toybuf[i] >= 32) && (toybuf[i] <= 126)) || (toybuf[i] == '\t')) {
        if (count > wlen) xputc(toybuf[i]);
        else {
          string[count] = toybuf[i];
          if (count == wlen) {
            if (toys.optflags & FLAG_f) xprintf("%s: ", filename);
            if (toys.optflags & FLAG_o)
              xprintf("%7lld ",(long long)(offset - wlen));
            xprintf("%s",string);
          }
          count++;
        }
      } else {
        if (count > wlen) xputc('\n');
        count = 0;
      }
    }
  }
  xclose(fd);
  free(string);
}

void strings_main(void)
{
  loopfiles(toys.optargs,  do_strings);
}