181c70bfb391e083ca1982c4e6887d2825c2d260
[oweals/busybox.git] / coreutils / 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 <assert.h>
59 #include "busybox.h"
60
61
62 #ifndef S_IFMT
63 static const int S_IFMT = 0170000;
64 #endif
65 #if !defined(S_ISBLK) && defined(S_IFBLK)
66 # define        S_ISBLK(m) (((m) & S_IFMT) == S_IFBLK)
67 #endif
68 #if !defined(S_ISCHR) && defined(S_IFCHR)
69 # define        S_ISCHR(m) (((m) & S_IFMT) == S_IFCHR)
70 #endif
71 #if !defined(S_ISDIR) && defined(S_IFDIR)
72 # define        S_ISDIR(m) (((m) & S_IFMT) == S_IFDIR)
73 #endif
74 #if !defined(S_ISREG) && defined(S_IFREG)
75 # define        S_ISREG(m) (((m) & S_IFMT) == S_IFREG)
76 #endif
77 #if !defined(S_ISFIFO) && defined(S_IFIFO)
78 # define        S_ISFIFO(m) (((m) & S_IFMT) == S_IFIFO)
79 #endif
80 #if !defined(S_ISLNK) && defined(S_IFLNK)
81 # define        S_ISLNK(m) (((m) & S_IFMT) == S_IFLNK)
82 #endif
83 #if !defined(S_ISSOCK) && defined(S_IFSOCK)
84 # define        S_ISSOCK(m) (((m) & S_IFMT) == S_IFSOCK)
85 #endif
86 #if !defined(S_ISMPB) && defined(S_IFMPB)       /* V7 */
87 # define S_ISMPB(m) (((m) & S_IFMT) == S_IFMPB)
88 # define S_ISMPC(m) (((m) & S_IFMT) == S_IFMPC)
89 #endif
90 #if !defined(S_ISNWK) && defined(S_IFNWK)       /* HP/UX */
91 # define S_ISNWK(m) (((m) & S_IFMT) == S_IFNWK)
92 #endif
93
94 #define IN_CTYPE_DOMAIN(c) 1
95
96 #define ISXDIGIT(c) (IN_CTYPE_DOMAIN (c) && isxdigit (c))
97 #define ISDIGIT_LOCALE(c) (IN_CTYPE_DOMAIN (c) && isdigit (c))
98 #define ISDIGIT(c) (((unsigned char) (c)) - '0' <= 9)
99
100 #define isodigit(c) ((c) >= '0' && (c) <= '7')
101 #define hextobin(c) ((c)>='a'&&(c)<='f' ? (c)-'a'+10 : (c)>='A'&&(c)<='F' ? (c)-'A'+10 : (c)-'0')
102 #define octtobin(c) ((c) - '0')
103
104 static double xstrtod __P((char *s));
105 static int print_esc __P((char *escstart));
106 static int print_formatted __P((char *format, int argc, char **argv));
107 static long xstrtol __P((char *s));
108 static unsigned long xstrtoul __P((char *s));
109 static void print_direc __P( (char *start, size_t length, 
110                         int field_width, int precision, char *argument));
111 static void print_esc_char __P((int c));
112 static void print_esc_string __P((char *str));
113
114 /* The value to return to the calling program.  */
115 static int exit_status;
116
117 int printf_main(int argc, char **argv)
118 {
119         char *format;
120         int args_used;
121
122         exit_status = 0;
123         if (argc <= 1 || **(argv + 1) == '-') {
124                 bb_show_usage();
125         }
126
127         format = argv[1];
128         argc -= 2;
129         argv += 2;
130
131         do {
132                 args_used = print_formatted(format, argc, argv);
133                 argc -= args_used;
134                 argv += args_used;
135         }
136         while (args_used > 0 && argc > 0);
137
138 /*
139   if (argc > 0)
140     fprintf(stderr, "excess args ignored");
141 */
142
143         return(exit_status);
144 }
145
146 /* Print the text in FORMAT, using ARGV (with ARGC elements) for
147    arguments to any `%' directives.
148    Return the number of elements of ARGV used.  */
149
150 static int print_formatted(char *format, int argc, char **argv)
151 {
152         int save_argc = argc;           /* Preserve original value.  */
153         char *f;                                        /* Pointer into `format'.  */
154         char *direc_start;                      /* Start of % directive.  */
155         size_t direc_length;            /* Length of % directive.  */
156         int field_width;                        /* Arg to first '*', or -1 if none.  */
157         int precision;                          /* Arg to second '*', or -1 if none.  */
158
159         for (f = format; *f; ++f) {
160                 switch (*f) {
161                 case '%':
162                         direc_start = f++;
163                         direc_length = 1;
164                         field_width = precision = -1;
165                         if (*f == '%') {
166                                 putchar('%');
167                                 break;
168                         }
169                         if (*f == 'b') {
170                                 if (argc > 0) {
171                                         print_esc_string(*argv);
172                                         ++argv;
173                                         --argc;
174                                 }
175                                 break;
176                         }
177                         if (strchr("-+ #", *f)) {
178                                 ++f;
179                                 ++direc_length;
180                         }
181                         if (*f == '*') {
182                                 ++f;
183                                 ++direc_length;
184                                 if (argc > 0) {
185                                         field_width = xstrtoul(*argv);
186                                         ++argv;
187                                         --argc;
188                                 } else
189                                         field_width = 0;
190                         } else
191                                 while (ISDIGIT(*f)) {
192                                         ++f;
193                                         ++direc_length;
194                                 }
195                         if (*f == '.') {
196                                 ++f;
197                                 ++direc_length;
198                                 if (*f == '*') {
199                                         ++f;
200                                         ++direc_length;
201                                         if (argc > 0) {
202                                                 precision = xstrtoul(*argv);
203                                                 ++argv;
204                                                 --argc;
205                                         } else
206                                                 precision = 0;
207                                 } else
208                                         while (ISDIGIT(*f)) {
209                                                 ++f;
210                                                 ++direc_length;
211                                         }
212                         }
213                         if (*f == 'l' || *f == 'L' || *f == 'h') {
214                                 ++f;
215                                 ++direc_length;
216                         }
217                         /*  
218                            if (!strchr ("diouxXfeEgGcs", *f))
219                            fprintf(stderr, "%%%c: invalid directive", *f);
220                          */
221                         ++direc_length;
222                         if (argc > 0) {
223                                 print_direc(direc_start, direc_length, field_width,
224                                                         precision, *argv);
225                                 ++argv;
226                                 --argc;
227                         } else
228                                 print_direc(direc_start, direc_length, field_width,
229                                                         precision, "");
230                         break;
231
232                 case '\\':
233                         f += print_esc(f);
234                         break;
235
236                 default:
237                         putchar(*f);
238                 }
239         }
240
241         return save_argc - argc;
242 }
243
244 /* Print a \ escape sequence starting at ESCSTART.
245    Return the number of characters in the escape sequence
246    besides the backslash. */
247
248 static int print_esc(char *escstart)
249 {
250         register char *p = escstart + 1;
251         int esc_value = 0;                      /* Value of \nnn escape. */
252         int esc_length;                         /* Length of \nnn escape. */
253
254         /* \0ooo and \xhhh escapes have maximum length of 3 chars. */
255         if (*p == 'x') {
256                 for (esc_length = 0, ++p;
257                          esc_length < 3 && ISXDIGIT(*p); ++esc_length, ++p)
258                         esc_value = esc_value * 16 + hextobin(*p);
259 /*      if (esc_length == 0)
260         fprintf(stderr, "missing hex in esc");
261 */
262                 putchar(esc_value);
263         } else if (*p == '0') {
264                 for (esc_length = 0, ++p;
265                          esc_length < 3 && isodigit(*p); ++esc_length, ++p)
266                         esc_value = esc_value * 8 + octtobin(*p);
267                 putchar(esc_value);
268         } else if (strchr("\"\\abcfnrtv", *p))
269                 print_esc_char(*p++);
270 /*  else
271     fprintf(stderr, "\\%c: invalid esc", *p);
272 */
273         return p - escstart - 1;
274 }
275
276 /* Output a single-character \ escape.  */
277
278 static void print_esc_char(int c)
279 {
280         switch (c) {
281         case 'a':                                       /* Alert. */
282                 putchar(7);
283                 break;
284         case 'b':                                       /* Backspace. */
285                 putchar(8);
286                 break;
287         case 'c':                                       /* Cancel the rest of the output. */
288                 exit(0);
289                 break;
290         case 'f':                                       /* Form feed. */
291                 putchar(12);
292                 break;
293         case 'n':                                       /* New line. */
294                 putchar(10);
295                 break;
296         case 'r':                                       /* Carriage return. */
297                 putchar(13);
298                 break;
299         case 't':                                       /* Horizontal tab. */
300                 putchar(9);
301                 break;
302         case 'v':                                       /* Vertical tab. */
303                 putchar(11);
304                 break;
305         default:
306                 putchar(c);
307                 break;
308         }
309 }
310
311 /* Print string STR, evaluating \ escapes. */
312
313 static void print_esc_string(char *str)
314 {
315         for (; *str; str++)
316                 if (*str == '\\')
317                         str += print_esc(str);
318                 else
319                         putchar(*str);
320 }
321
322 static void
323 print_direc(char *start, size_t length, int field_width, int precision,
324                         char *argument)
325 {
326         char *p;                                        /* Null-terminated copy of % directive. */
327
328         p = xmalloc((unsigned) (length + 1));
329         strncpy(p, start, length);
330         p[length] = 0;
331
332         switch (p[length - 1]) {
333         case 'd':
334         case 'i':
335                 if (field_width < 0) {
336                         if (precision < 0)
337                                 printf(p, xstrtol(argument));
338                         else
339                                 printf(p, precision, xstrtol(argument));
340                 } else {
341                         if (precision < 0)
342                                 printf(p, field_width, xstrtol(argument));
343                         else
344                                 printf(p, field_width, precision, xstrtol(argument));
345                 }
346                 break;
347
348         case 'o':
349         case 'u':
350         case 'x':
351         case 'X':
352                 if (field_width < 0) {
353                         if (precision < 0)
354                                 printf(p, xstrtoul(argument));
355                         else
356                                 printf(p, precision, xstrtoul(argument));
357                 } else {
358                         if (precision < 0)
359                                 printf(p, field_width, xstrtoul(argument));
360                         else
361                                 printf(p, field_width, precision, xstrtoul(argument));
362                 }
363                 break;
364
365         case 'f':
366         case 'e':
367         case 'E':
368         case 'g':
369         case 'G':
370                 if (field_width < 0) {
371                         if (precision < 0)
372                                 printf(p, xstrtod(argument));
373                         else
374                                 printf(p, precision, xstrtod(argument));
375                 } else {
376                         if (precision < 0)
377                                 printf(p, field_width, xstrtod(argument));
378                         else
379                                 printf(p, field_width, precision, xstrtod(argument));
380                 }
381                 break;
382
383         case 'c':
384                 printf(p, *argument);
385                 break;
386
387         case 's':
388                 if (field_width < 0) {
389                         if (precision < 0)
390                                 printf(p, argument);
391                         else
392                                 printf(p, precision, argument);
393                 } else {
394                         if (precision < 0)
395                                 printf(p, field_width, argument);
396                         else
397                                 printf(p, field_width, precision, argument);
398                 }
399                 break;
400         }
401
402         free(p);
403 }
404
405 static unsigned long xstrtoul(char *arg)
406 {
407         unsigned long result;
408         char *endptr;
409         //int errno_save = errno;
410
411         assert(arg!=NULL);
412
413         errno = 0;
414         result = strtoul(arg, &endptr, 0);
415         if (errno != 0 || *endptr!='\0' || endptr==arg)
416                 fprintf(stderr, "%s", arg);
417         //errno = errno_save;
418         return result;
419 }
420
421 static long xstrtol(char *arg)
422 {
423         long result;
424         char *endptr;
425         //int errno_save = errno;
426
427         assert(arg!=NULL);
428
429         errno = 0;
430         result = strtoul(arg, &endptr, 0);
431         if (errno != 0 || *endptr!='\0' || endptr==arg)
432                 fprintf(stderr, "%s", arg);
433         //errno = errno_save;
434         return result;
435 }
436
437 static double xstrtod(char *arg)
438 {
439         double result;
440         char *endptr;
441         //int errno_save = errno;
442
443         assert(arg!=NULL);
444
445         errno = 0;
446         result = strtod(arg, &endptr);
447         if (errno != 0 || *endptr!='\0' || endptr==arg)
448                 fprintf(stderr, "%s", arg);
449         //errno = errno_save;
450         return result;
451 }
452