Some #include updates.
[platform/upstream/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 "internal.h"
51 #include <unistd.h>
52 #include <stdio.h>
53 #include <sys/types.h>
54 #include <string.h>
55 #include <errno.h>
56 #include <stdlib.h>
57 #include <fcntl.h>
58 #include <ctype.h>
59
60
61 #ifndef S_IFMT
62 # define 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 #ifdef isblank
96 # define ISBLANK(c) (IN_CTYPE_DOMAIN (c) && isblank (c))
97 #else
98 # define ISBLANK(c) ((c) == ' ' || (c) == '\t')
99 #endif
100 #ifdef isgraph
101 # define ISGRAPH(c) (IN_CTYPE_DOMAIN (c) && isgraph (c))
102 #else
103 # define ISGRAPH(c) (IN_CTYPE_DOMAIN (c) && isprint (c) && !isspace (c))
104 #endif
105
106 #define ISPRINT(c) (IN_CTYPE_DOMAIN (c) && isprint (c))
107 #define ISALNUM(c) (IN_CTYPE_DOMAIN (c) && isalnum (c))
108 #define ISALPHA(c) (IN_CTYPE_DOMAIN (c) && isalpha (c))
109 #define ISCNTRL(c) (IN_CTYPE_DOMAIN (c) && iscntrl (c))
110 #define ISLOWER(c) (IN_CTYPE_DOMAIN (c) && islower (c))
111 #define ISPUNCT(c) (IN_CTYPE_DOMAIN (c) && ispunct (c))
112 #define ISSPACE(c) (IN_CTYPE_DOMAIN (c) && isspace (c))
113 #define ISUPPER(c) (IN_CTYPE_DOMAIN (c) && isupper (c))
114 #define ISXDIGIT(c) (IN_CTYPE_DOMAIN (c) && isxdigit (c))
115 #define ISDIGIT_LOCALE(c) (IN_CTYPE_DOMAIN (c) && isdigit (c))
116 #define ISDIGIT(c) ((unsigned) (c) - '0' <= 9)
117
118 #define isodigit(c) ((c) >= '0' && (c) <= '7')
119 #define hextobin(c) ((c)>='a'&&(c)<='f' ? (c)-'a'+10 : (c)>='A'&&(c)<='F' ? (c)-'A'+10 : (c)-'0')
120 #define octtobin(c) ((c) - '0')
121
122 static double xstrtod __P((char *s));
123 static int print_esc __P((char *escstart));
124 static int print_formatted __P((char *format, int argc, char **argv));
125 static long xstrtol __P((char *s));
126 static unsigned long xstrtoul __P((char *s));
127 static void print_direc
128 __P(
129
130         (char *start, size_t length, int field_width, int precision,
131          char *argument));
132 static void print_esc_char __P((int c));
133 static void print_esc_string __P((char *str));
134 static void verify __P((char *s, char *end));
135
136 /* The value to return to the calling program.  */
137 static int exit_status;
138
139 int printf_main(int argc, char **argv)
140 {
141         char *format;
142         int args_used;
143
144         exit_status = 0;
145         if (argc <= 1 || **(argv + 1) == '-') {
146                 usage(printf_usage);
147         }
148
149         format = argv[1];
150         argc -= 2;
151         argv += 2;
152
153         do {
154                 args_used = print_formatted(format, argc, argv);
155                 argc -= args_used;
156                 argv += args_used;
157         }
158         while (args_used > 0 && argc > 0);
159
160 /*
161   if (argc > 0)
162     fprintf(stderr, "excess args ignored");
163 */
164
165         return(exit_status);
166 }
167
168 /* Print the text in FORMAT, using ARGV (with ARGC elements) for
169    arguments to any `%' directives.
170    Return the number of elements of ARGV used.  */
171
172 static int print_formatted(char *format, int argc, char **argv)
173 {
174         int save_argc = argc;           /* Preserve original value.  */
175         char *f;                                        /* Pointer into `format'.  */
176         char *direc_start;                      /* Start of % directive.  */
177         size_t direc_length;            /* Length of % directive.  */
178         int field_width;                        /* Arg to first '*', or -1 if none.  */
179         int precision;                          /* Arg to second '*', or -1 if none.  */
180
181         for (f = format; *f; ++f) {
182                 switch (*f) {
183                 case '%':
184                         direc_start = f++;
185                         direc_length = 1;
186                         field_width = precision = -1;
187                         if (*f == '%') {
188                                 putchar('%');
189                                 break;
190                         }
191                         if (*f == 'b') {
192                                 if (argc > 0) {
193                                         print_esc_string(*argv);
194                                         ++argv;
195                                         --argc;
196                                 }
197                                 break;
198                         }
199                         if (strchr("-+ #", *f)) {
200                                 ++f;
201                                 ++direc_length;
202                         }
203                         if (*f == '*') {
204                                 ++f;
205                                 ++direc_length;
206                                 if (argc > 0) {
207                                         field_width = xstrtoul(*argv);
208                                         ++argv;
209                                         --argc;
210                                 } else
211                                         field_width = 0;
212                         } else
213                                 while (ISDIGIT(*f)) {
214                                         ++f;
215                                         ++direc_length;
216                                 }
217                         if (*f == '.') {
218                                 ++f;
219                                 ++direc_length;
220                                 if (*f == '*') {
221                                         ++f;
222                                         ++direc_length;
223                                         if (argc > 0) {
224                                                 precision = xstrtoul(*argv);
225                                                 ++argv;
226                                                 --argc;
227                                         } else
228                                                 precision = 0;
229                                 } else
230                                         while (ISDIGIT(*f)) {
231                                                 ++f;
232                                                 ++direc_length;
233                                         }
234                         }
235                         if (*f == 'l' || *f == 'L' || *f == 'h') {
236                                 ++f;
237                                 ++direc_length;
238                         }
239                         /*  
240                            if (!strchr ("diouxXfeEgGcs", *f))
241                            fprintf(stderr, "%%%c: invalid directive", *f);
242                          */
243                         ++direc_length;
244                         if (argc > 0) {
245                                 print_direc(direc_start, direc_length, field_width,
246                                                         precision, *argv);
247                                 ++argv;
248                                 --argc;
249                         } else
250                                 print_direc(direc_start, direc_length, field_width,
251                                                         precision, "");
252                         break;
253
254                 case '\\':
255                         f += print_esc(f);
256                         break;
257
258                 default:
259                         putchar(*f);
260                 }
261         }
262
263         return save_argc - argc;
264 }
265
266 /* Print a \ escape sequence starting at ESCSTART.
267    Return the number of characters in the escape sequence
268    besides the backslash. */
269
270 static int print_esc(char *escstart)
271 {
272         register char *p = escstart + 1;
273         int esc_value = 0;                      /* Value of \nnn escape. */
274         int esc_length;                         /* Length of \nnn escape. */
275
276         /* \0ooo and \xhhh escapes have maximum length of 3 chars. */
277         if (*p == 'x') {
278                 for (esc_length = 0, ++p;
279                          esc_length < 3 && ISXDIGIT(*p); ++esc_length, ++p)
280                         esc_value = esc_value * 16 + hextobin(*p);
281 /*      if (esc_length == 0)
282         fprintf(stderr, "missing hex in esc");
283 */
284                 putchar(esc_value);
285         } else if (*p == '0') {
286                 for (esc_length = 0, ++p;
287                          esc_length < 3 && isodigit(*p); ++esc_length, ++p)
288                         esc_value = esc_value * 8 + octtobin(*p);
289                 putchar(esc_value);
290         } else if (strchr("\"\\abcfnrtv", *p))
291                 print_esc_char(*p++);
292 /*  else
293     fprintf(stderr, "\\%c: invalid esc", *p);
294 */
295         return p - escstart - 1;
296 }
297
298 /* Output a single-character \ escape.  */
299
300 static void print_esc_char(int c)
301 {
302         switch (c) {
303         case 'a':                                       /* Alert. */
304                 putchar(7);
305                 break;
306         case 'b':                                       /* Backspace. */
307                 putchar(8);
308                 break;
309         case 'c':                                       /* Cancel the rest of the output. */
310                 exit(0);
311                 break;
312         case 'f':                                       /* Form feed. */
313                 putchar(12);
314                 break;
315         case 'n':                                       /* New line. */
316                 putchar(10);
317                 break;
318         case 'r':                                       /* Carriage return. */
319                 putchar(13);
320                 break;
321         case 't':                                       /* Horizontal tab. */
322                 putchar(9);
323                 break;
324         case 'v':                                       /* Vertical tab. */
325                 putchar(11);
326                 break;
327         default:
328                 putchar(c);
329                 break;
330         }
331 }
332
333 /* Print string STR, evaluating \ escapes. */
334
335 static void print_esc_string(char *str)
336 {
337         for (; *str; str++)
338                 if (*str == '\\')
339                         str += print_esc(str);
340                 else
341                         putchar(*str);
342 }
343
344 static void
345 print_direc(char *start, size_t length, int field_width, int precision,
346                         char *argument)
347 {
348         char *p;                                        /* Null-terminated copy of % directive. */
349
350         p = xmalloc((unsigned) (length + 1));
351         strncpy(p, start, length);
352         p[length] = 0;
353
354         switch (p[length - 1]) {
355         case 'd':
356         case 'i':
357                 if (field_width < 0) {
358                         if (precision < 0)
359                                 printf(p, xstrtol(argument));
360                         else
361                                 printf(p, precision, xstrtol(argument));
362                 } else {
363                         if (precision < 0)
364                                 printf(p, field_width, xstrtol(argument));
365                         else
366                                 printf(p, field_width, precision, xstrtol(argument));
367                 }
368                 break;
369
370         case 'o':
371         case 'u':
372         case 'x':
373         case 'X':
374                 if (field_width < 0) {
375                         if (precision < 0)
376                                 printf(p, xstrtoul(argument));
377                         else
378                                 printf(p, precision, xstrtoul(argument));
379                 } else {
380                         if (precision < 0)
381                                 printf(p, field_width, xstrtoul(argument));
382                         else
383                                 printf(p, field_width, precision, xstrtoul(argument));
384                 }
385                 break;
386
387         case 'f':
388         case 'e':
389         case 'E':
390         case 'g':
391         case 'G':
392                 if (field_width < 0) {
393                         if (precision < 0)
394                                 printf(p, xstrtod(argument));
395                         else
396                                 printf(p, precision, xstrtod(argument));
397                 } else {
398                         if (precision < 0)
399                                 printf(p, field_width, xstrtod(argument));
400                         else
401                                 printf(p, field_width, precision, xstrtod(argument));
402                 }
403                 break;
404
405         case 'c':
406                 printf(p, *argument);
407                 break;
408
409         case 's':
410                 if (field_width < 0) {
411                         if (precision < 0)
412                                 printf(p, argument);
413                         else
414                                 printf(p, precision, argument);
415                 } else {
416                         if (precision < 0)
417                                 printf(p, field_width, argument);
418                         else
419                                 printf(p, field_width, precision, argument);
420                 }
421                 break;
422         }
423
424         free(p);
425 }
426
427 static unsigned long xstrtoul(char *s)
428 {
429         char *end;
430         unsigned long val;
431
432         errno = 0;
433         val = strtoul(s, &end, 0);
434         verify(s, end);
435         return val;
436 }
437
438 static long xstrtol(char *s)
439 {
440         char *end;
441         long val;
442
443         errno = 0;
444         val = strtol(s, &end, 0);
445         verify(s, end);
446         return val;
447 }
448
449 static double xstrtod(char *s)
450 {
451         char *end;
452         double val;
453
454         errno = 0;
455         val = strtod(s, &end);
456         verify(s, end);
457         return val;
458 }
459
460 static void verify(char *s, char *end)
461 {
462         if (errno) {
463                 fprintf(stderr, "%s", s);
464                 exit_status = 1;
465         } else if (*end) {
466                 /*
467                    if (s == end)
468                    fprintf(stderr, "%s: expected numeric", s);
469                    else
470                    fprintf(stderr, "%s: not completely converted", s);
471                  */
472                 exit_status = 1;
473         }
474 }