cut: code shrink
[busybox-git.git] / miscutils / strings.c
blobbd1850cbb9429ff160106e2c9aef5101c5f760c2
1 /* vi: set sw=4 ts=4: */
2 /*
3 * strings implementation for busybox
5 * Copyright 2003 Tito Ragusa <farmatito@tiscali.it>
7 * Licensed under GPLv2 or later, see file LICENSE in this source tree.
8 */
9 //config:config STRINGS
10 //config: bool "strings (4.8 kb)"
11 //config: default y
12 //config: help
13 //config: strings prints the printable character sequences for each file
14 //config: specified.
16 //applet:IF_STRINGS(APPLET(strings, BB_DIR_USR_BIN, BB_SUID_DROP))
18 //kbuild:lib-$(CONFIG_STRINGS) += strings.o
20 //usage:#define strings_trivial_usage
21 //usage: "[-fo] [-t o|d|x] [-n LEN] [FILE]..."
22 //usage:#define strings_full_usage "\n\n"
23 //usage: "Display printable strings in a binary file\n"
24 //We usually don't bother user with "nop" options. They work, but are not shown:
25 ////usage: "\n -a Scan whole file (default)"
26 //unimplemented alternative is -d: Only strings from initialized, loaded data sections
27 //usage: "\n -f Precede strings with filenames"
28 //usage: "\n -o Precede strings with octal offsets"
29 //usage: "\n -t o|d|x Precede strings with offsets in base 8/10/16"
30 //usage: "\n -n LEN At least LEN characters form a string (default 4)"
32 #include "libbb.h"
34 #define WHOLE_FILE 1
35 #define PRINT_NAME 2
36 #define PRINT_OFFSET 4
37 #define SIZE 8
38 #define PRINT_RADIX 16
40 int strings_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
41 int strings_main(int argc UNUSED_PARAM, char **argv)
43 int n, c;
44 exitcode_t status = EXIT_SUCCESS;
45 unsigned count;
46 off_t offset;
47 FILE *file;
48 char *string;
49 const char *fmt = "%s: ";
50 const char *n_arg = "4";
51 /* default for -o */
52 const char *radix = "o";
53 char *radix_fmt;
55 getopt32(argv, "afon:t:", &n_arg, &radix);
56 /* -a is our default behaviour */
57 /*argc -= optind;*/
58 argv += optind;
60 n = xatou_range(n_arg, 1, INT_MAX);
61 string = xzalloc(n + 1);
62 n--;
64 if ((radix[0] != 'd' && radix[0] != 'o' && radix[0] != 'x') || radix[1] != 0)
65 bb_show_usage();
67 radix_fmt = xasprintf("%%7"OFF_FMT"%s ", radix);
69 if (!*argv) {
70 fmt = "{%s}: ";
71 *--argv = (char *)bb_msg_standard_input;
74 do {
75 file = fopen_or_warn_stdin(*argv);
76 if (!file) {
77 status = EXIT_FAILURE;
78 continue;
80 offset = 0;
81 count = 0;
82 do {
83 c = fgetc(file);
84 if (isprint_asciionly(c) || c == '\t') {
85 if (count > n) {
86 bb_putchar(c);
87 } else {
88 string[count] = c;
89 if (count == n) {
90 if (option_mask32 & PRINT_NAME) {
91 printf(fmt, *argv);
93 if (option_mask32 & (PRINT_OFFSET | PRINT_RADIX)) {
94 printf(radix_fmt, offset - n);
96 fputs_stdout(string);
98 count++;
100 } else {
101 if (count > n) {
102 bb_putchar('\n');
104 count = 0;
106 offset++;
107 } while (c != EOF);
108 fclose_if_not_stdin(file);
109 } while (*++argv);
111 if (ENABLE_FEATURE_CLEAN_UP) {
112 free(string);
113 free(radix_fmt);
116 fflush_stdout_and_exit(status);