don't whine if all we need to do is remove a bg job
[oweals/busybox.git] / printf.c
1 /* vi: set sw=4 ts=4: */
2 /* printf - format and print data
3    Copyright (C) 90, 91, 92, 93, 94, 95, 1996 Free Software Foundation, Inc.
4
5    This program is free software; you can redistribute it and/or modify
6    it under the terms of the GNU General Public License as published by
7    the Free Software Foundation; either version 2, or (at your option)
8    any later version.
9
10    This program is distributed in the hope that it will be useful,
11    but WITHOUT ANY WARRANTY; without even the implied warranty of
12    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13    GNU General Public License for more details.
14
15    You should have received a copy of the GNU General Public License
16    along with this program; if not, write to the Free Software Foundation,
17    Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.  */
18
19 /* Usage: printf format [argument...]
20
21    A front end to the printf function that lets it be used from the shell.
22
23    Backslash escapes:
24
25    \" = double quote
26    \\ = backslash
27    \a = alert (bell)
28    \b = backspace
29    \c = produce no further output
30    \f = form feed
31    \n = new line
32    \r = carriage return
33    \t = horizontal tab
34    \v = vertical tab
35    \0ooo = octal number (ooo is 0 to 3 digits)
36    \xhhh = hexadecimal number (hhh is 1 to 3 digits)
37
38    Additional directive:
39
40    %b = print an argument string, interpreting backslash escapes
41
42    The `format' argument is re-used as many times as necessary
43    to convert all of the given arguments.
44
45    David MacKenzie <djm@gnu.ai.mit.edu> */
46
47
48 //   19990508 Busy Boxed! Dave Cinege
49
50 #include <unistd.h>
51 #include <stdio.h>
52 #include <sys/types.h>
53 #include <string.h>
54 #include <errno.h>
55 #include <stdlib.h>
56 #include <fcntl.h>
57 #include <ctype.h>
58 #include "busybox.h"
59
60
61 #ifndef S_IFMT
62 static const int S_IFMT = 0170000;
63 #endif
64 #if !defined(S_ISBLK) && defined(S_IFBLK)
65 # define        S_ISBLK(m) (((m) & S_IFMT) == S_IFBLK)
66 #endif
67 #if !defined(S_ISCHR) && defined(S_IFCHR)
68 # define        S_ISCHR(m) (((m) & S_IFMT) == S_IFCHR)
69 #endif
70 #if !defined(S_ISDIR) && defined(S_IFDIR)
71 # define        S_ISDIR(m) (((m) & S_IFMT) == S_IFDIR)
72 #endif
73 #if !defined(S_ISREG) && defined(S_IFREG)
74 # define        S_ISREG(m) (((m) & S_IFMT) == S_IFREG)
75 #endif
76 #if !defined(S_ISFIFO) && defined(S_IFIFO)
77 # define        S_ISFIFO(m) (((m) & S_IFMT) == S_IFIFO)
78 #endif
79 #if !defined(S_ISLNK) && defined(S_IFLNK)
80 # define        S_ISLNK(m) (((m) & S_IFMT) == S_IFLNK)
81 #endif
82 #if !defined(S_ISSOCK) && defined(S_IFSOCK)
83 # define        S_ISSOCK(m) (((m) & S_IFMT) == S_IFSOCK)
84 #endif
85 #if !defined(S_ISMPB) && defined(S_IFMPB)       /* V7 */
86 # define S_ISMPB(m) (((m) & S_IFMT) == S_IFMPB)
87 # define S_ISMPC(m) (((m) & S_IFMT) == S_IFMPC)
88 #endif
89 #if !defined(S_ISNWK) && defined(S_IFNWK)       /* HP/UX */
90 # define S_ISNWK(m) (((m) & S_IFMT) == S_IFNWK)
91 #endif
92
93 #define IN_CTYPE_DOMAIN(c) 1
94
95 #define ISXDIGIT(c) (IN_CTYPE_DOMAIN (c) && isxdigit (c))
96 #define ISDIGIT_LOCALE(c) (IN_CTYPE_DOMAIN (c) && isdigit (c))
97 #define ISDIGIT(c) (((unsigned char) (c)) - '0' <= 9)
98
99 #define isodigit(c) ((c) >= '0' && (c) <= '7')
100 #define hextobin(c) ((c)>='a'&&(c)<='f' ? (c)-'a'+10 : (c)>='A'&&(c)<='F' ? (c)-'A'+10 : (c)-'0')
101 #define octtobin(c) ((c) - '0')
102
103 static double xstrtod __P((char *s));
104 static int print_esc __P((char *escstart));
105 static int print_formatted __P((char *format, int argc, char **argv));
106 static long xstrtol __P((char *s));
107 static unsigned long xstrtoul __P((char *s));
108 static void print_direc
109 __P(
110
111         (char *start, size_t length, int field_width, int precision,
112          char *argument));
113 static void print_esc_char __P((int c));
114 static void print_esc_string __P((char *str));
115 static void verify __P((char *s, char *end));
116
117 /* The value to return to the calling program.  */
118 static int exit_status;
119
120 int printf_main(int argc, char **argv)
121 {
122         char *format;
123         int args_used;
124
125         exit_status = 0;
126         if (argc <= 1 || **(argv + 1) == '-') {
127                 show_usage();
128         }
129
130         format = argv[1];
131         argc -= 2;
132         argv += 2;
133
134         do {
135                 args_used = print_formatted(format, argc, argv);
136                 argc -= args_used;
137                 argv += args_used;
138         }
139         while (args_used > 0 && argc > 0);
140
141 /*
142   if (argc > 0)
143     fprintf(stderr, "excess args ignored");
144 */
145
146         return(exit_status);
147 }
148
149 /* Print the text in FORMAT, using ARGV (with ARGC elements) for
150    arguments to any `%' directives.
151    Return the number of elements of ARGV used.  */
152
153 static int print_formatted(char *format, int argc, char **argv)
154 {
155         int save_argc = argc;           /* Preserve original value.  */
156         char *f;                                        /* Pointer into `format'.  */
157         char *direc_start;                      /* Start of % directive.  */
158         size_t direc_length;            /* Length of % directive.  */
159         int field_width;                        /* Arg to first '*', or -1 if none.  */
160         int precision;                          /* Arg to second '*', or -1 if none.  */
161
162         for (f = format; *f; ++f) {
163                 switch (*f) {
164                 case '%':
165                         direc_start = f++;
166                         direc_length = 1;
167                         field_width = precision = -1;
168                         if (*f == '%') {
169                                 putchar('%');
170                                 break;
171                         }
172                         if (*f == 'b') {
173                                 if (argc > 0) {
174                                         print_esc_string(*argv);
175                                         ++argv;
176                                         --argc;
177                                 }
178                                 break;
179                         }
180                         if (strchr("-+ #", *f)) {
181                                 ++f;
182                                 ++direc_length;
183                         }
184                         if (*f == '*') {
185                                 ++f;
186                                 ++direc_length;
187                                 if (argc > 0) {
188                                         field_width = xstrtoul(*argv);
189                                         ++argv;
190                                         --argc;
191                                 } else
192                                         field_width = 0;
193                         } else
194                                 while (ISDIGIT(*f)) {
195                                         ++f;
196                                         ++direc_length;
197                                 }
198                         if (*f == '.') {
199                                 ++f;
200                                 ++direc_length;
201                                 if (*f == '*') {
202                                         ++f;
203                                         ++direc_length;
204                                         if (argc > 0) {
205                                                 precision = xstrtoul(*argv);
206                                                 ++argv;
207                                                 --argc;
208                                         } else
209                                                 precision = 0;
210                                 } else
211                                         while (ISDIGIT(*f)) {
212                                                 ++f;
213                                                 ++direc_length;
214                                         }
215                         }
216                         if (*f == 'l' || *f == 'L' || *f == 'h') {
217                                 ++f;
218                                 ++direc_length;
219                         }
220                         /*  
221                            if (!strchr ("diouxXfeEgGcs", *f))
222                            fprintf(stderr, "%%%c: invalid directive", *f);
223                          */
224                         ++direc_length;
225                         if (argc > 0) {
226                                 print_direc(direc_start, direc_length, field_width,
227                                                         precision, *argv);
228                                 ++argv;
229                                 --argc;
230                         } else
231                                 print_direc(direc_start, direc_length, field_width,
232                                                         precision, "");
233                         break;
234
235                 case '\\':
236                         f += print_esc(f);
237                         break;
238
239                 default:
240                         putchar(*f);
241                 }
242         }
243
244         return save_argc - argc;
245 }
246
247 /* Print a \ escape sequence starting at ESCSTART.
248    Return the number of characters in the escape sequence
249    besides the backslash. */
250
251 static int print_esc(char *escstart)
252 {
253         register char *p = escstart + 1;
254         int esc_value = 0;                      /* Value of \nnn escape. */
255         int esc_length;                         /* Length of \nnn escape. */
256
257         /* \0ooo and \xhhh escapes have maximum length of 3 chars. */
258         if (*p == 'x') {
259                 for (esc_length = 0, ++p;
260                          esc_length < 3 && ISXDIGIT(*p); ++esc_length, ++p)
261                         esc_value = esc_value * 16 + hextobin(*p);
262 /*      if (esc_length == 0)
263         fprintf(stderr, "missing hex in esc");
264 */
265                 putchar(esc_value);
266         } else if (*p == '0') {
267                 for (esc_length = 0, ++p;
268                          esc_length < 3 && isodigit(*p); ++esc_length, ++p)
269                         esc_value = esc_value * 8 + octtobin(*p);
270                 putchar(esc_value);
271         } else if (strchr("\"\\abcfnrtv", *p))
272                 print_esc_char(*p++);
273 /*  else
274     fprintf(stderr, "\\%c: invalid esc", *p);
275 */
276         return p - escstart - 1;
277 }
278
279 /* Output a single-character \ escape.  */
280
281 static void print_esc_char(int c)
282 {
283         switch (c) {
284         case 'a':                                       /* Alert. */
285                 putchar(7);
286                 break;
287         case 'b':                                       /* Backspace. */
288                 putchar(8);
289                 break;
290         case 'c':                                       /* Cancel the rest of the output. */
291                 exit(0);
292                 break;
293         case 'f':                                       /* Form feed. */
294                 putchar(12);
295                 break;
296         case 'n':                                       /* New line. */
297                 putchar(10);
298                 break;
299         case 'r':                                       /* Carriage return. */
300                 putchar(13);
301                 break;
302         case 't':                                       /* Horizontal tab. */
303                 putchar(9);
304                 break;
305         case 'v':                                       /* Vertical tab. */
306                 putchar(11);
307                 break;
308         default:
309                 putchar(c);
310                 break;
311         }
312 }
313
314 /* Print string STR, evaluating \ escapes. */
315
316 static void print_esc_string(char *str)
317 {
318         for (; *str; str++)
319                 if (*str == '\\')
320                         str += print_esc(str);
321                 else
322                         putchar(*str);
323 }
324
325 static void
326 print_direc(char *start, size_t length, int field_width, int precision,
327                         char *argument)
328 {
329         char *p;                                        /* Null-terminated copy of % directive. */
330
331         p = xmalloc((unsigned) (length + 1));
332         strncpy(p, start, length);
333         p[length] = 0;
334
335         switch (p[length - 1]) {
336         case 'd':
337         case 'i':
338                 if (field_width < 0) {
339                         if (precision < 0)
340                                 printf(p, xstrtol(argument));
341                         else
342                                 printf(p, precision, xstrtol(argument));
343                 } else {
344                         if (precision < 0)
345                                 printf(p, field_width, xstrtol(argument));
346                         else
347                                 printf(p, field_width, precision, xstrtol(argument));
348                 }
349                 break;
350
351         case 'o':
352         case 'u':
353         case 'x':
354         case 'X':
355                 if (field_width < 0) {
356                         if (precision < 0)
357                                 printf(p, xstrtoul(argument));
358                         else
359                                 printf(p, precision, xstrtoul(argument));
360                 } else {
361                         if (precision < 0)
362                                 printf(p, field_width, xstrtoul(argument));
363                         else
364                                 printf(p, field_width, precision, xstrtoul(argument));
365                 }
366                 break;
367
368         case 'f':
369         case 'e':
370         case 'E':
371         case 'g':
372         case 'G':
373                 if (field_width < 0) {
374                         if (precision < 0)
375                                 printf(p, xstrtod(argument));
376                         else
377                                 printf(p, precision, xstrtod(argument));
378                 } else {
379                         if (precision < 0)
380                                 printf(p, field_width, xstrtod(argument));
381                         else
382                                 printf(p, field_width, precision, xstrtod(argument));
383                 }
384                 break;
385
386         case 'c':
387                 printf(p, *argument);
388                 break;
389
390         case 's':
391                 if (field_width < 0) {
392                         if (precision < 0)
393                                 printf(p, argument);
394                         else
395                                 printf(p, precision, argument);
396                 } else {
397                         if (precision < 0)
398                                 printf(p, field_width, argument);
399                         else
400                                 printf(p, field_width, precision, argument);
401                 }
402                 break;
403         }
404
405         free(p);
406 }
407
408 static unsigned long xstrtoul(char *s)
409 {
410         char *end;
411         unsigned long val;
412
413         errno = 0;
414         val = strtoul(s, &end, 0);
415         verify(s, end);
416         return val;
417 }
418
419 static long xstrtol(char *s)
420 {
421         char *end;
422         long val;
423
424         errno = 0;
425         val = strtol(s, &end, 0);
426         verify(s, end);
427         return val;
428 }
429
430 static double xstrtod(char *s)
431 {
432         char *end;
433         double val;
434
435         errno = 0;
436         val = strtod(s, &end);
437         verify(s, end);
438         return val;
439 }
440
441 static void verify(char *s, char *end)
442 {
443         if (errno) {
444                 fprintf(stderr, "%s", s);
445                 exit_status = 1;
446         } else if (*end) {
447                 /*
448                    if (s == end)
449                    fprintf(stderr, "%s: expected numeric", s);
450                    else
451                    fprintf(stderr, "%s: not completely converted", s);
452                  */
453                 exit_status = 1;
454         }
455 }