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. 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
29 * @(#) Copyright (c) 1989, 1993 The Regents of the University of California. All rights reserved.
30 * @(#)printf.c 8.1 (Berkeley) 7/20/93
31 * $FreeBSD: src/usr.bin/printf/printf.c,v 1.50 2010/12/29 21:38:00 jilles Exp $
34 #include <sys/types.h>
47 #define main printfcmd
48 #include "bltin/bltin.h"
52 #define PF(f, func) do { \
56 asprintf(&b, f, fieldwidth, precision, func); \
58 asprintf(&b, f, fieldwidth, func); \
60 asprintf(&b, f, precision, func); \
62 asprintf(&b, f, func); \
69 static int asciicode(void);
70 static char *printf_doformat(char *, int *);
71 static int escape(char *, int, size_t *);
72 static int getchr(void);
73 static int getfloating(long double *, int);
74 static int getint(int *);
75 static int getnum(intmax_t *, uintmax_t *, int);
78 static char *mknum(char *, char);
79 static void usage(void);
84 main(int argc, char **argv)
87 int chopped, end, rval;
88 char *format, *fmt, *start;
91 setlocale(LC_ALL, "");
95 * We may not use getopt(3) because calling
96 * "printf -f%s oo" may not result in an invalid
98 * However common usage and other implementations seem
99 * to indicate that we need to allow -- as a discardable
102 if (argc > 1 && strcmp(argv[1], "--") == 0) {
118 * Basic algorithm is to scan the format string for conversion
119 * specifications -- once one is found, find out if the field
120 * width or precision is a '*'; if it is, gather up value. Note,
121 * format strings are reused as necessary to use up the provided
122 * arguments, arguments of zero/null string are provided to use
123 * up the format string.
125 fmt = format = *argv;
126 chopped = escape(fmt, 1, &len); /* backslash interpretation */
131 while (fmt < format + len) {
133 fwrite(start, 1, fmt - start, stdout);
139 fmt = printf_doformat(fmt, &rval);
154 warnx("missing format character");
160 fwrite(start, 1, fmt - start, stdout);
161 if (chopped || !*gargv) {
167 /* Restart at the beginning of the format string. */
176 printf_doformat(char *start, int *rval)
178 static const char skip1[] = "#'-+ 0";
179 static const char skip2[] = "0123456789";
181 int fieldwidth, haveprec, havewidth, mod_ldbl, precision;
185 /* skip to field width */
186 fmt += strspn(fmt, skip1);
188 if (getint(&fieldwidth))
195 /* skip to possible '.', get following precision */
196 fmt += strspn(fmt, skip2);
199 /* precision present? */
202 if (getint(&precision))
209 /* skip to conversion char */
210 fmt += strspn(fmt, skip2);
215 warnx("missing format character");
220 * Look for a length modifier. POSIX doesn't have these, so
221 * we only support them for floating-point conversions, which
222 * are extensions. This is useful because the L modifier can
223 * be used to gain extra range and precision, while omitting
224 * it is more likely to produce consistent results on different
225 * architectures. This is not so important for integers
226 * because overflow is the only bad thing that can happen to
227 * them, but consider the command printf %a 1.1
232 if (!strchr("aAeEfFgG", *fmt)) {
233 warnx("bad modifier L for %%%c", *fmt);
249 p = strdup(getstr());
251 warnx("%s", strerror(ENOMEM));
254 getout = escape(p, 0, &len);
277 case 'd': case 'i': case 'o': case 'u': case 'x': case 'X': {
283 signedconv = (convch == 'd' || convch == 'i');
284 if ((f = mknum(start, convch)) == NULL)
286 if (getnum(&val, &uval, signedconv))
297 case 'a': case 'A': {
300 if (getfloating(&p, mod_ldbl))
305 PF(start, (double)p);
309 warnx("illegal format character %c", convch);
317 mknum(char *str, char ch)
320 static size_t copy_size;
324 len = strlen(str) + 2;
325 if (len > copy_size) {
326 newlen = ((len + 1023) >> 10) << 10;
327 if ((newcopy = realloc(copy, newlen)) == NULL)
329 warnx("%s", strerror(ENOMEM));
336 memmove(copy, str, len - 3);
339 copy[len - 1] = '\0';
344 escape(char *fmt, int percent, size_t *len)
349 for (save = store = fmt; (c = *fmt); ++fmt, ++store) {
355 case '\0': /* EOS, user error */
360 case '\\': /* backslash */
361 case '\'': /* single quote */
364 case 'a': /* bell/alert */
367 case 'b': /* backspace */
374 case 'f': /* form-feed */
377 case 'n': /* newline */
380 case 'r': /* carriage-return */
383 case 't': /* horizontal tab */
386 case 'v': /* vertical tab */
390 case '0': case '1': case '2': case '3':
391 case '4': case '5': case '6': case '7':
392 c = (!percent && *fmt == '0') ? 4 : 3;
394 c-- && *fmt >= '0' && *fmt <= '7'; ++fmt) {
399 if (percent && value == '%') {
420 return ((int)**gargv++);
438 if (getnum(&val, &uval, 1))
441 if (val < INT_MIN || val > INT_MAX) {
442 warnx("%s: %s", *gargv, strerror(ERANGE));
450 getnum(intmax_t *ip, uintmax_t *uip, int signedconv)
459 if (**gargv == '"' || **gargv == '\'') {
469 *ip = strtoimax(*gargv, &ep, 0);
471 *uip = strtoumax(*gargv, &ep, 0);
473 warnx("%s: expected numeric value", *gargv);
476 else if (*ep != '\0') {
477 warnx("%s: not completely converted", *gargv);
480 if (errno == ERANGE) {
481 warnx("%s: %s", *gargv, strerror(ERANGE));
489 getfloating(long double *dp, int mod_ldbl)
498 if (**gargv == '"' || **gargv == '\'') {
505 *dp = strtold(*gargv, &ep);
507 *dp = strtod(*gargv, &ep);
509 warnx("%s: expected numeric value", *gargv);
511 } else if (*ep != '\0') {
512 warnx("%s: not completely converted", *gargv);
515 if (errno == ERANGE) {
516 warnx("%s: %s", *gargv, strerror(ERANGE));
529 if (ch == '\'' || ch == '"')
538 fprintf(stderr, "usage: printf format [arguments ...]\n");