2 * Copyright (c) 1989, 1993
3 * The Regents of the University of California. All rights reserved.
5 * Redistribution and use in source and binary forms, with or without
6 * modification, are permitted provided that the following conditions
8 * 1. Redistributions of source code must retain the above copyright
9 * notice, this list of conditions and the following disclaimer.
10 * 2. Redistributions in binary form must reproduce the above copyright
11 * notice, this list of conditions and the following disclaimer in the
12 * documentation and/or other materials provided with the distribution.
13 * 4. Neither the name of the University nor the names of its contributors
14 * may be used to endorse or promote products derived from this software
15 * without specific prior written permission.
17 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
18 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
19 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
20 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
21 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
22 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
23 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
24 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
25 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
26 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
30 * Important: This file is used both as a standalone program /usr/bin/printf
31 * and as a builtin for /bin/sh (#define SHELL).
36 static char const copyright[] =
37 "@(#) Copyright (c) 1989, 1993\n\
38 The Regents of the University of California. All rights reserved.\n";
44 static char const sccsid[] = "@(#)printf.c 8.1 (Berkeley) 7/20/93";
46 static const char rcsid[] =
50 #include <sys/types.h>
64 #define main printfcmd
65 #include "bltin/bltin.h"
70 #define PF(f, func) do { \
74 (void)asprintf(&b, f, fieldwidth, precision, func); \
76 (void)asprintf(&b, f, fieldwidth, func); \
78 (void)asprintf(&b, f, precision, func); \
80 (void)asprintf(&b, f, func); \
82 (void)fputs(b, stdout); \
87 static int asciicode(void);
88 static char *printf_doformat(char *, int *);
89 static int escape(char *, int, size_t *);
90 static int getchr(void);
91 static int getfloating(long double *, int);
92 static int getint(int *);
93 static int getnum(intmax_t *, uintmax_t *, int);
96 static char *mknum(char *, char);
97 static void usage(void);
102 main(int argc, char *argv[])
105 int chopped, end, rval;
106 char *format, *fmt, *start;
110 (void) setlocale(LC_ALL, "");
115 argc -= argptr - argv;
118 while ((ch = getopt(argc, argv, "")) != -1)
138 * Basic algorithm is to scan the format string for conversion
139 * specifications -- once one is found, find out if the field
140 * width or precision is a '*'; if it is, gather up value. Note,
141 * format strings are reused as necessary to use up the provided
142 * arguments, arguments of zero/null string are provided to use
143 * up the format string.
145 fmt = format = *argv;
146 chopped = escape(fmt, 1, &len); /* backslash interpretation */
151 while (fmt < format + len) {
153 fwrite(start, 1, fmt - start, stdout);
159 fmt = printf_doformat(fmt, &rval);
174 warnx("missing format character");
180 fwrite(start, 1, fmt - start, stdout);
181 if (chopped || !*gargv) {
187 /* Restart at the beginning of the format string. */
196 printf_doformat(char *start, int *rval)
198 static const char skip1[] = "#'-+ 0";
199 static const char skip2[] = "0123456789";
201 int fieldwidth, haveprec, havewidth, mod_ldbl, precision;
205 /* skip to field width */
206 fmt += strspn(fmt, skip1);
208 if (getint(&fieldwidth))
215 /* skip to possible '.', get following precision */
216 fmt += strspn(fmt, skip2);
219 /* precision present? */
222 if (getint(&precision))
229 /* skip to conversion char */
230 fmt += strspn(fmt, skip2);
235 warnx("missing format character");
240 * Look for a length modifier. POSIX doesn't have these, so
241 * we only support them for floating-point conversions, which
242 * are extensions. This is useful because the L modifier can
243 * be used to gain extra range and precision, while omitting
244 * it is more likely to produce consistent results on different
245 * architectures. This is not so important for integers
246 * because overflow is the only bad thing that can happen to
247 * them, but consider the command printf %a 1.1
252 if (!strchr("aAeEfFgG", *fmt)) {
253 warnx("bad modifier L for %%%c", *fmt);
269 p = strdup(getstr());
271 warnx("%s", strerror(ENOMEM));
274 getout = escape(p, 0, &len);
297 case 'd': case 'i': case 'o': case 'u': case 'x': case 'X': {
303 signedconv = (convch == 'd' || convch == 'i');
304 if ((f = mknum(start, convch)) == NULL)
306 if (getnum(&val, &uval, signedconv))
317 case 'a': case 'A': {
320 if (getfloating(&p, mod_ldbl))
325 PF(start, (double)p);
329 warnx("illegal format character %c", convch);
337 mknum(char *str, char ch)
340 static size_t copy_size;
344 len = strlen(str) + 2;
345 if (len > copy_size) {
346 newlen = ((len + 1023) >> 10) << 10;
347 if ((newcopy = realloc(copy, newlen)) == NULL)
349 warnx("%s", strerror(ENOMEM));
356 memmove(copy, str, len - 3);
359 copy[len - 1] = '\0';
364 escape(char *fmt, int percent, size_t *len)
366 char *save, *store, c;
369 for (save = store = fmt; ((c = *fmt) != 0); ++fmt, ++store) {
375 case '\0': /* EOS, user error */
380 case '\\': /* backslash */
381 case '\'': /* single quote */
384 case 'a': /* bell/alert */
387 case 'b': /* backspace */
394 case 'f': /* form-feed */
397 case 'n': /* newline */
400 case 'r': /* carriage-return */
403 case 't': /* horizontal tab */
406 case 'v': /* vertical tab */
410 case '0': case '1': case '2': case '3':
411 case '4': case '5': case '6': case '7':
412 c = (!percent && *fmt == '0') ? 4 : 3;
414 c-- && *fmt >= '0' && *fmt <= '7'; ++fmt) {
419 if (percent && value == '%') {
423 *store = (char)value;
440 return ((int)**gargv++);
458 if (getnum(&val, &uval, 1))
461 if (val < INT_MIN || val > INT_MAX) {
462 warnx("%s: %s", *gargv, strerror(ERANGE));
470 getnum(intmax_t *ip, uintmax_t *uip, int signedconv)
479 if (**gargv == '"' || **gargv == '\'') {
489 *ip = strtoimax(*gargv, &ep, 0);
491 *uip = strtoumax(*gargv, &ep, 0);
493 warnx("%s: expected numeric value", *gargv);
496 else if (*ep != '\0') {
497 warnx("%s: not completely converted", *gargv);
500 if (errno == ERANGE) {
501 warnx("%s: %s", *gargv, strerror(ERANGE));
509 getfloating(long double *dp, int mod_ldbl)
518 if (**gargv == '"' || **gargv == '\'') {
525 *dp = strtold(*gargv, &ep);
527 *dp = strtod(*gargv, &ep);
529 warnx("%s: expected numeric value", *gargv);
531 } else if (*ep != '\0') {
532 warnx("%s: not completely converted", *gargv);
535 if (errno == ERANGE) {
536 warnx("%s: %s", *gargv, strerror(ERANGE));
550 ch = (unsigned char)**gargv;
551 if (ch == '\'' || ch == '"') {
552 memset(&mbs, 0, sizeof(mbs));
553 switch (mbrtowc(&wch, *gargv + 1, MB_LEN_MAX, &mbs)) {
556 wch = (unsigned char)gargv[0][1];
571 (void)fprintf(stderr, "usage: printf format [arguments ...]\n");