xref: /original-bsd/usr.bin/strings/strings.c (revision d25e1985)
1 static char *sccsid = "@(#)strings.c	4.1 (Berkeley) 10/01/80";
2 #include <stdio.h>
3 #include <a.out.h>
4 #include <ctype.h>
5 
6 long	ftell();
7 
8 /*
9  * strings
10  */
11 
12 struct	exec header;
13 
14 char	*infile = "Standard input";
15 int	oflg;
16 int	asdata;
17 long	offset;
18 int	minlength = 4;
19 
20 main(argc, argv)
21 	int argc;
22 	char *argv[];
23 {
24 
25 	argc--, argv++;
26 	while (argc > 0 && argv[0][0] == '-') {
27 		register int i;
28 		if (argv[0][1] == 0)
29 			asdata++;
30 		else for (i = 1; argv[0][i] != 0; i++) switch (argv[0][i]) {
31 
32 		case 'o':
33 			oflg++;
34 			break;
35 
36 		case 'a':
37 			asdata++;
38 			break;
39 
40 		default:
41 			if (!isdigit(argv[0][i])) {
42 				fprintf(stderr, "Usage: strings [ -a ] [ -o ] [ -# ] [ file ... ]\n");
43 				exit(1);
44 			}
45 			minlength = argv[0][i] - '0';
46 			for (i++; isdigit(argv[0][i]); i++)
47 				minlength = minlength * 10 + argv[0][i] - '0';
48 			i--;
49 			break;
50 		}
51 		argc--, argv++;
52 	}
53 	do {
54 		if (argc > 0) {
55 			if (freopen(argv[0], "r", stdin) == NULL) {
56 				perror(argv[0]);
57 				exit(1);
58 			}
59 			infile = argv[0];
60 			argc--, argv++;
61 		}
62 		fseek(stdin, (long) 0, 0);
63 		if (asdata ||
64 		    fread((char *)&header, sizeof header, 1, stdin) != 1 ||
65 		    N_BADMAG(header)) {
66 			fseek(stdin, (long) 0, 0);
67 			find((long) 100000000L);
68 			continue;
69 		}
70 		fseek(stdin, (long) N_TXTOFF(header)+header.a_text, 1);
71 		find((long) header.a_data);
72 	} while (argc > 0);
73 }
74 
75 find(cnt)
76 	long cnt;
77 {
78 	static char buf[BUFSIZ];
79 	register char *cp;
80 	register int c, cc;
81 
82 	cp = buf, cc = 0;
83 	for (; cnt != 0; cnt--) {
84 		c = getc(stdin);
85 		if (c == '\n' || dirt(c) || cnt == 0) {
86 			if (cp > buf && cp[-1] == '\n')
87 				--cp;
88 			*cp++ = 0;
89 			if (cp > &buf[minlength]) {
90 				if (oflg)
91 					printf("%7D ", ftell(stdin) - cc - 1);
92 				printf("%s\n", buf);
93 			}
94 			cp = buf, cc = 0;
95 		} else {
96 			if (cp < &buf[sizeof buf - 2])
97 				*cp++ = c;
98 			cc++;
99 		}
100 		if (ferror(stdin) || feof(stdin))
101 			break;
102 	}
103 }
104 
105 dirt(c)
106 	int c;
107 {
108 
109 	switch (c) {
110 
111 	case '\n':
112 	case '\f':
113 		return (0);
114 
115 	case 0177:
116 		return (1);
117 
118 	default:
119 		return (c > 0200 || c < ' ');
120 	}
121 }
122