BSD 3 development
[unix-history] / usr / src / cmd / strings.c
CommitLineData
7cddb6ac
BJ
1#include <stdio.h>
2#include <a.out.h>
3#include <ctype.h>
4
5long ftell();
6
7/*
8 * Strings - extract strings from an object file for whatever
9 *
10 * Bill Joy UCB
11 * April 22, 1978
12 *
13 * The algorithm is to look for sequences of "non-junk" characters
14 * The variable "minlen" is the minimum length string printed.
15 * This helps get rid of garbage.
16 * Default minimum string length is 4 characters.
17 */
18
19struct exec header;
20
21char *infile = "Standard input";
22int oflg;
23int asdata;
24long offset;
25int minlength = 4;
26
27main(argc, argv)
28 int argc;
29 char *argv[];
30{
31
32 argc--, argv++;
33 while (argc > 0 && argv[0][0] == '-') {
34 register int i;
35 if (argv[0][1] == 0)
36 asdata++;
37 else for (i = 1; argv[0][i] != 0; i++) switch (argv[0][i]) {
38
39 case 'o':
40 oflg++;
41 break;
42
43 case 'a':
44 asdata++;
45 break;
46
47 default:
48 if (!isdigit(argv[0][i])) {
49 fprintf(stderr, "Usage: strings [ - ] [ -o ] [ -# ] [ file ... ]\n");
50 exit(1);
51 }
52 minlength = argv[0][i] - '0';
53 for (i++; isdigit(argv[0][i]); i++)
54 minlength = minlength * 10 + argv[0][i] - '0';
55 i--;
56 break;
57 }
58 argc--, argv++;
59 }
60 do {
61 if (argc > 0) {
62 if (freopen(argv[0], "r", stdin) == NULL) {
63 perror(argv[0]);
64 exit(1);
65 }
66 infile = argv[0];
67 argc--, argv++;
68 }
69 fseek(stdin, (long) 0, 0);
70 if (asdata ||
71 fread((char *)&header, sizeof header, 1, stdin) != 1 ||
72 !ismagic(header.a_magic)) {
73 fseek(stdin, (long) 0, 0);
74 find((long) 100000000L);
75 continue;
76 }
77 fseek(stdin, (long) header.a_text, 1);
78 find((long) header.a_data);
79 } while (argc > 0);
80}
81
82find(cnt)
83 long cnt;
84{
85 static char buf[BUFSIZ];
86 register char *cp;
87 register int c, cc;
88
89 cp = buf, cc = 0;
90 for (; cnt != 0; cnt--) {
91 c = getc(stdin);
92 if (c == '\n' || dirt(c) || cnt == 0) {
93 if (cp > buf && cp[-1] == '\n')
94 --cp;
95 *cp++ = 0;
96 if (cp > &buf[minlength]) {
97 if (oflg)
98 printf("%7D ", ftell(stdin) - cc - 1);
99 printf("%s\n", buf);
100 }
101 cp = buf, cc = 0;
102 } else {
103 if (cp < &buf[sizeof buf - 2])
104 *cp++ = c;
105 cc++;
106 }
107 if (ferror(stdin) || feof(stdin))
108 break;
109 }
110}
111
112dirt(c)
113 int c;
114{
115
116 switch (c) {
117
118 case '\n':
119 case '\f':
120 return (0);
121
122 case 0177:
123 return (1);
124
125 default:
126 return (c > 0200 || c < ' ');
127 }
128}
129
130ismagic(a)
131 int a;
132{
133
134 switch (a) {
135
136 case A_MAGIC1:
137 case A_MAGIC2:
138 case A_MAGIC3:
139 case A_MAGIC4:
140 return (1);
141 }
142 return (0);
143}