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 * 3. All advertising materials mentioning features or use of this software
14 * must display the following acknowledgement:
15 * This product includes software developed by the University of
16 * California, Berkeley and its contributors.
17 * 4. Neither the name of the University nor the names of its contributors
18 * may be used to endorse or promote products derived from this software
19 * without specific prior written permission.
21 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
22 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
23 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
24 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
25 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
26 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
27 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
28 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
29 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
30 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
33 * @(#) Copyright (c) 1989, 1993 The Regents of the University of California. All rights reserved.
34 * @(#)printf.c 8.1 (Berkeley) 7/20/93
35 * $FreeBSD: src/usr.bin/printf/printf.c,v 1.50 2010/12/29 21:38:00 jilles Exp $
38 #include <sys/types.h>
51 #define main printfcmd
52 #include "bltin/bltin.h"
56 #define PF(f, func) do { \
60 asprintf(&b, f, fieldwidth, precision, func); \
62 asprintf(&b, f, fieldwidth, func); \
64 asprintf(&b, f, precision, func); \
66 asprintf(&b, f, func); \
73 static int asciicode(void);
74 static char *printf_doformat(char *, int *);
75 static int escape(char *, int, size_t *);
76 static int getchr(void);
77 static int getfloating(long double *, int);
78 static int getint(int *);
79 static int getnum(intmax_t *, uintmax_t *, int);
82 static char *mknum(char *, char);
83 static void usage(void);
88 main(int argc, char **argv)
91 int chopped, end, rval;
92 char *format, *fmt, *start;
95 setlocale(LC_ALL, "");
99 * We may not use getopt(3) because calling
100 * "printf -f%s oo" may not result in an invalid
102 * However common usage and other implementations seem
103 * to indicate that we need to allow -- as a discardable
106 if (argc > 1 && strcmp(argv[1], "--") == 0) {
122 * Basic algorithm is to scan the format string for conversion
123 * specifications -- once one is found, find out if the field
124 * width or precision is a '*'; if it is, gather up value. Note,
125 * format strings are reused as necessary to use up the provided
126 * arguments, arguments of zero/null string are provided to use
127 * up the format string.
129 fmt = format = *argv;
130 chopped = escape(fmt, 1, &len); /* backslash interpretation */
135 while (fmt < format + len) {
137 fwrite(start, 1, fmt - start, stdout);
143 fmt = printf_doformat(fmt, &rval);
158 warnx("missing format character");
164 fwrite(start, 1, fmt - start, stdout);
165 if (chopped || !*gargv) {
171 /* Restart at the beginning of the format string. */
180 printf_doformat(char *start, int *rval)
182 static const char skip1[] = "#'-+ 0";
183 static const char skip2[] = "0123456789";
185 int fieldwidth, haveprec, havewidth, mod_ldbl, precision;
189 /* skip to field width */
190 fmt += strspn(fmt, skip1);
192 if (getint(&fieldwidth))
199 /* skip to possible '.', get following precision */
200 fmt += strspn(fmt, skip2);
203 /* precision present? */
206 if (getint(&precision))
213 /* skip to conversion char */
214 fmt += strspn(fmt, skip2);
219 warnx("missing format character");
224 * Look for a length modifier. POSIX doesn't have these, so
225 * we only support them for floating-point conversions, which
226 * are extensions. This is useful because the L modifier can
227 * be used to gain extra range and precision, while omitting
228 * it is more likely to produce consistent results on different
229 * architectures. This is not so important for integers
230 * because overflow is the only bad thing that can happen to
231 * them, but consider the command printf %a 1.1
236 if (!strchr("aAeEfFgG", *fmt)) {
237 warnx("bad modifier L for %%%c", *fmt);
253 p = strdup(getstr());
255 warnx("%s", strerror(ENOMEM));
258 getout = escape(p, 0, &len);
281 case 'd': case 'i': case 'o': case 'u': case 'x': case 'X': {
287 signedconv = (convch == 'd' || convch == 'i');
288 if ((f = mknum(start, convch)) == NULL)
290 if (getnum(&val, &uval, signedconv))
301 case 'a': case 'A': {
304 if (getfloating(&p, mod_ldbl))
309 PF(start, (double)p);
313 warnx("illegal format character %c", convch);
321 mknum(char *str, char ch)
324 static size_t copy_size;
328 len = strlen(str) + 2;
329 if (len > copy_size) {
330 newlen = ((len + 1023) >> 10) << 10;
331 if ((newcopy = realloc(copy, newlen)) == NULL)
333 warnx("%s", strerror(ENOMEM));
340 memmove(copy, str, len - 3);
343 copy[len - 1] = '\0';
348 escape(char *fmt, int percent, size_t *len)
353 for (save = store = fmt; (c = *fmt); ++fmt, ++store) {
359 case '\0': /* EOS, user error */
364 case '\\': /* backslash */
365 case '\'': /* single quote */
368 case 'a': /* bell/alert */
371 case 'b': /* backspace */
378 case 'f': /* form-feed */
381 case 'n': /* newline */
384 case 'r': /* carriage-return */
387 case 't': /* horizontal tab */
390 case 'v': /* vertical tab */
394 case '0': case '1': case '2': case '3':
395 case '4': case '5': case '6': case '7':
396 c = (!percent && *fmt == '0') ? 4 : 3;
398 c-- && *fmt >= '0' && *fmt <= '7'; ++fmt) {
403 if (percent && value == '%') {
424 return ((int)**gargv++);
442 if (getnum(&val, &uval, 1))
445 if (val < INT_MIN || val > INT_MAX) {
446 warnx("%s: %s", *gargv, strerror(ERANGE));
454 getnum(intmax_t *ip, uintmax_t *uip, int signedconv)
463 if (**gargv == '"' || **gargv == '\'') {
473 *ip = strtoimax(*gargv, &ep, 0);
475 *uip = strtoumax(*gargv, &ep, 0);
477 warnx("%s: expected numeric value", *gargv);
480 else if (*ep != '\0') {
481 warnx("%s: not completely converted", *gargv);
484 if (errno == ERANGE) {
485 warnx("%s: %s", *gargv, strerror(ERANGE));
493 getfloating(long double *dp, int mod_ldbl)
502 if (**gargv == '"' || **gargv == '\'') {
509 *dp = strtold(*gargv, &ep);
511 *dp = strtod(*gargv, &ep);
513 warnx("%s: expected numeric value", *gargv);
515 } else if (*ep != '\0') {
516 warnx("%s: not completely converted", *gargv);
519 if (errno == ERANGE) {
520 warnx("%s: %s", *gargv, strerror(ERANGE));
533 if (ch == '\'' || ch == '"')
542 fprintf(stderr, "usage: printf format [arguments ...]\n");