morpheus-base

morpheus base system
git clone git://git.2f30.org/morpheus-base
Log | Files | Refs

strings.c (1032B)


      1 /* See LICENSE file for copyright and license details. */
      2 #include <ctype.h>
      3 #include <stdio.h>
      4 #include <stdlib.h>
      5 
      6 #include "util.h"
      7 
      8 static void dostrings(FILE *fp, const char *fname);
      9 
     10 static void
     11 usage(void)
     12 {
     13 	eprintf("usage: %s [file ...]\n", argv0);
     14 }
     15 
     16 int
     17 main(int argc, char *argv[])
     18 {
     19 	FILE *fp;
     20 	int ret = 0;
     21 
     22 	ARGBEGIN {
     23 	default:
     24 		usage();
     25 	} ARGEND;
     26 
     27 	if (argc == 0) {
     28 		dostrings(stdin, "<stdin>");
     29 	} else {
     30 		for (; argc > 0; argc--, argv++) {
     31 			if (!(fp = fopen(argv[0], "r"))) {
     32 				weprintf("fopen %s:", argv[0]);
     33 				ret = 1;
     34 				continue;
     35 			}
     36 			dostrings(fp, argv[0]);
     37 			fclose(fp);
     38 		}
     39 	}
     40 	return ret;
     41 }
     42 
     43 static void
     44 dostrings(FILE *fp, const char *fname)
     45 {
     46 	unsigned char buf[BUFSIZ];
     47 	int c, i = 0;
     48 	off_t offset = 0;
     49 
     50 	do {
     51 		offset++;
     52 		if (isprint(c = getc(fp)))
     53 			buf[i++] = c;
     54 		if ((!isprint(c) && i >= 6) || i == sizeof(buf) - 1) {
     55 			buf[i] = '\0';
     56 			printf("%8ld: %s\n", (long)offset - i - 1, buf);
     57 			i = 0;
     58 		}
     59 	} while (c != EOF);
     60 	if (ferror(fp))
     61 		eprintf("%s: read error:", fname);
     62 }