Home | History | Annotate | Line # | Download | only in stdio
vfprintf.c revision 1.33
      1 /*	$NetBSD: vfprintf.c,v 1.33 2000/07/08 14:57:57 sommerfeld Exp $	*/
      2 
      3 /*-
      4  * Copyright (c) 1990 The Regents of the University of California.
      5  * All rights reserved.
      6  *
      7  * This code is derived from software contributed to Berkeley by
      8  * Chris Torek.
      9  *
     10  * Redistribution and use in source and binary forms, with or without
     11  * modification, are permitted provided that the following conditions
     12  * are met:
     13  * 1. Redistributions of source code must retain the above copyright
     14  *    notice, this list of conditions and the following disclaimer.
     15  * 2. Redistributions in binary form must reproduce the above copyright
     16  *    notice, this list of conditions and the following disclaimer in the
     17  *    documentation and/or other materials provided with the distribution.
     18  * 3. All advertising materials mentioning features or use of this software
     19  *    must display the following acknowledgement:
     20  *	This product includes software developed by the University of
     21  *	California, Berkeley and its contributors.
     22  * 4. Neither the name of the University nor the names of its contributors
     23  *    may be used to endorse or promote products derived from this software
     24  *    without specific prior written permission.
     25  *
     26  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
     27  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
     28  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
     29  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
     30  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
     31  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
     32  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
     33  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
     34  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
     35  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
     36  * SUCH DAMAGE.
     37  */
     38 
     39 #include <sys/cdefs.h>
     40 #if defined(LIBC_SCCS) && !defined(lint)
     41 #if 0
     42 static char *sccsid = "@(#)vfprintf.c	5.50 (Berkeley) 12/16/92";
     43 #else
     44 __RCSID("$NetBSD: vfprintf.c,v 1.33 2000/07/08 14:57:57 sommerfeld Exp $");
     45 #endif
     46 #endif /* LIBC_SCCS and not lint */
     47 
     48 /*
     49  * Actual printf innards.
     50  *
     51  * This code is large and complicated...
     52  */
     53 
     54 #include "namespace.h"
     55 #include <sys/types.h>
     56 
     57 #include <assert.h>
     58 #include <errno.h>
     59 #include <stdio.h>
     60 #include <stdlib.h>
     61 #include <string.h>
     62 
     63 #if __STDC__
     64 #include <stdarg.h>
     65 #else
     66 #include <varargs.h>
     67 #endif
     68 
     69 #include "local.h"
     70 #include "fvwrite.h"
     71 #include "extern.h"
     72 #include "reentrant.h"
     73 
     74 static int __sprint __P((FILE *, struct __suio *));
     75 static int __sbprintf __P((FILE *, const char *, va_list))
     76      __attribute__((__format__(__printf__, 2, 0)));
     77 
     78 /*
     79  * Flush out all the vectors defined by the given uio,
     80  * then reset it so that it can be reused.
     81  */
     82 static int
     83 __sprint(fp, uio)
     84 	FILE *fp;
     85 	struct __suio *uio;
     86 {
     87 	int err;
     88 
     89 	_DIAGASSERT(fp != NULL);
     90 	_DIAGASSERT(uio != NULL);
     91 
     92 	if (uio->uio_resid == 0) {
     93 		uio->uio_iovcnt = 0;
     94 		return (0);
     95 	}
     96 	err = __sfvwrite(fp, uio);
     97 	uio->uio_resid = 0;
     98 	uio->uio_iovcnt = 0;
     99 	return (err);
    100 }
    101 
    102 /*
    103  * Helper function for `fprintf to unbuffered unix file': creates a
    104  * temporary buffer.  We only work on write-only files; this avoids
    105  * worries about ungetc buffers and so forth.
    106  */
    107 static int
    108 __sbprintf(fp, fmt, ap)
    109 	FILE *fp;
    110 	const char *fmt;
    111 	va_list ap;
    112 {
    113 	int ret;
    114 	FILE fake;
    115 	unsigned char buf[BUFSIZ];
    116 
    117 	_DIAGASSERT(fp != NULL);
    118 	_DIAGASSERT(fmt != NULL);
    119 
    120 	/* copy the important variables */
    121 	fake._flags = fp->_flags & ~__SNBF;
    122 	fake._file = fp->_file;
    123 	fake._cookie = fp->_cookie;
    124 	fake._write = fp->_write;
    125 
    126 	/* set up the buffer */
    127 	fake._bf._base = fake._p = buf;
    128 	fake._bf._size = fake._w = sizeof(buf);
    129 	fake._lbfsize = 0;	/* not actually used, but Just In Case */
    130 
    131 	/* do the work, then copy any error status */
    132 	ret = vfprintf(&fake, fmt, ap);
    133 	if (ret >= 0 && fflush(&fake))
    134 		ret = -1;
    135 	if (fake._flags & __SERR)
    136 		fp->_flags |= __SERR;
    137 	return (ret);
    138 }
    139 
    140 
    141 #ifdef FLOATING_POINT
    142 #include <locale.h>
    143 #include <math.h>
    144 #include "floatio.h"
    145 
    146 #define	BUF		(MAXEXP+MAXFRACT+1)	/* + decimal point */
    147 #define	DEFPREC		6
    148 
    149 static char *cvt __P((double, int, int, char *, int *, int, int *));
    150 static int exponent __P((char *, int, int));
    151 
    152 #else /* no FLOATING_POINT */
    153 
    154 #define	BUF		40
    155 
    156 #endif /* FLOATING_POINT */
    157 
    158 #ifdef lint
    159 static __inline void *__UNCONST __P((const void *));
    160 static __inline void *
    161 __UNCONST(v)
    162 	const void *v;
    163 {
    164 	/* LINTED */
    165 	return (void *) v;
    166 }
    167 #else
    168 #define __UNCONST(v)	(void *)(v)
    169 #endif
    170 
    171 /*
    172  * Macros for converting digits to letters and vice versa
    173  */
    174 #define	to_digit(c)	((c) - '0')
    175 #define is_digit(c)	((unsigned)to_digit(c) <= 9)
    176 #define	to_char(n)	((char)((n) + '0'))
    177 
    178 /*
    179  * Flags used during conversion.
    180  */
    181 #define	ALT		0x001		/* alternate form */
    182 #define	HEXPREFIX	0x002		/* add 0x or 0X prefix */
    183 #define	LADJUST		0x004		/* left adjustment */
    184 #define	LONGDBL		0x008		/* long double; unimplemented */
    185 #define	LONGINT		0x010		/* long integer */
    186 #define	QUADINT		0x020		/* quad integer */
    187 #define	SHORTINT	0x040		/* short integer */
    188 #define	ZEROPAD		0x080		/* zero (as opposed to blank) pad */
    189 #define FPT		0x100		/* Floating point number */
    190 int
    191 vfprintf(fp, fmt0, ap)
    192 	FILE *fp;
    193 	const char *fmt0;
    194 	_BSD_VA_LIST_ ap;
    195 {
    196 	const char *fmt;/* format string */
    197 	int ch;	/* character from fmt */
    198 	int n, m;	/* handy integers (short term usage) */
    199 	const char *cp;	/* handy char pointer (short term usage) */
    200 	char *bp;	/* handy char pointer (short term usage) */
    201 	struct __siov *iovp;/* for PRINT macro */
    202 	int flags;	/* flags as above */
    203 	int ret;		/* return value accumulator */
    204 	int width;		/* width from format (%8d), or 0 */
    205 	int prec;		/* precision from format (%.3d), or -1 */
    206 	char sign;		/* sign prefix (' ', '+', '-', or \0) */
    207 	wchar_t wc;
    208 #ifdef FLOATING_POINT
    209 	char *decimal_point = localeconv()->decimal_point;
    210 	char softsign;		/* temporary negative sign for floats */
    211 	double _double = 0;	/* double precision arguments %[eEfgG] */
    212 	int expt;		/* integer value of exponent */
    213 	int expsize = 0;	/* character count for expstr */
    214 	int ndig;		/* actual number of digits returned by cvt */
    215 	char expstr[7];		/* buffer for exponent string */
    216 #endif
    217 
    218 #ifdef __GNUC__			/* gcc has builtin quad type (long long) SOS */
    219 #define	quad_t	  long long
    220 #define	u_quad_t  unsigned long long
    221 #endif
    222 
    223 	u_quad_t _uquad;	/* integer arguments %[diouxX] */
    224 	enum { OCT, DEC, HEX } base;/* base for [diouxX] conversion */
    225 	int dprec;		/* a copy of prec if [diouxX], 0 otherwise */
    226 	int realsz;		/* field size expanded by dprec */
    227 	int size;		/* size of converted field or string */
    228 	char *xdigs = NULL;	/* digits for [xX] conversion */
    229 #define NIOV 8
    230 	struct __suio uio;	/* output information: summary */
    231 	struct __siov iov[NIOV];/* ... and individual io vectors */
    232 	char buf[BUF];		/* space for %c, %[diouxX], %[eEfgG] */
    233 	char ox[2];		/* space for 0x hex-prefix */
    234 
    235 	/*
    236 	 * Choose PADSIZE to trade efficiency vs. size.  If larger printf
    237 	 * fields occur frequently, increase PADSIZE and make the initialisers
    238 	 * below longer.
    239 	 */
    240 #define	PADSIZE	16		/* pad chunk size */
    241 	static const char blanks[PADSIZE] =
    242 	 {' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' '};
    243 	static const char zeroes[PADSIZE] =
    244 	 {'0','0','0','0','0','0','0','0','0','0','0','0','0','0','0','0'};
    245 
    246 	/*
    247 	 * BEWARE, these `goto error' on error, and PAD uses `n'.
    248 	 */
    249 #define	PRINT(ptr, len) { \
    250 	iovp->iov_base = __UNCONST(ptr); \
    251 	iovp->iov_len = (len); \
    252 	uio.uio_resid += (len); \
    253 	iovp++; \
    254 	if (++uio.uio_iovcnt >= NIOV) { \
    255 		if (__sprint(fp, &uio)) \
    256 			goto error; \
    257 		iovp = iov; \
    258 	} \
    259 }
    260 #define	PAD(howmany, with) { \
    261 	if ((n = (howmany)) > 0) { \
    262 		while (n > PADSIZE) { \
    263 			PRINT(with, PADSIZE); \
    264 			n -= PADSIZE; \
    265 		} \
    266 		PRINT(with, n); \
    267 	} \
    268 }
    269 #define	FLUSH() { \
    270 	if (uio.uio_resid && __sprint(fp, &uio)) \
    271 		goto error; \
    272 	uio.uio_iovcnt = 0; \
    273 	iovp = iov; \
    274 }
    275 
    276 	/*
    277 	 * To extend shorts properly, we need both signed and unsigned
    278 	 * argument extraction methods.
    279 	 */
    280 #define	SARG() \
    281 	(flags&QUADINT ? va_arg(ap, quad_t) : \
    282 	    flags&LONGINT ? va_arg(ap, long) : \
    283 	    flags&SHORTINT ? (long)(short)va_arg(ap, int) : \
    284 	    (long)va_arg(ap, int))
    285 #define	UARG() \
    286 	(flags&QUADINT ? va_arg(ap, u_quad_t) : \
    287 	    flags&LONGINT ? va_arg(ap, u_long) : \
    288 	    flags&SHORTINT ? (u_long)(u_short)va_arg(ap, int) : \
    289 	    (u_long)va_arg(ap, u_int))
    290 
    291 	_DIAGASSERT(fp != NULL);
    292 	_DIAGASSERT(fmt0 != NULL);
    293 
    294 	FLOCKFILE(fp);
    295 
    296 	/* sorry, fprintf(read_only_file, "") returns -1, not 0 */
    297 	if (cantwrite(fp)) {
    298 		errno = EBADF;
    299 		FUNLOCKFILE(fp);
    300 		return (-1);
    301 	}
    302 
    303 	/* optimise fprintf(stderr) (and other unbuffered Unix files) */
    304 	if ((fp->_flags & (__SNBF|__SWR|__SRW)) == (__SNBF|__SWR) &&
    305 	    fp->_file >= 0) {
    306 		ret = __sbprintf(fp, fmt0, ap);
    307 		FUNLOCKFILE(fp);
    308 		return (ret);
    309 	}
    310 
    311 	fmt = fmt0;
    312 	uio.uio_iov = iovp = iov;
    313 	uio.uio_resid = 0;
    314 	uio.uio_iovcnt = 0;
    315 	ret = 0;
    316 
    317 	/*
    318 	 * Scan the format for conversions (`%' character).
    319 	 */
    320 	for (;;) {
    321 		cp = fmt;
    322 		while ((n = mbtowc(&wc, fmt, MB_CUR_MAX)) > 0) {
    323 			fmt += n;
    324 			if (wc == '%') {
    325 				fmt--;
    326 				break;
    327 			}
    328 		}
    329 		if ((m = fmt - cp) != 0) {
    330 			PRINT(cp, m);
    331 			ret += m;
    332 		}
    333 		if (n <= 0)
    334 			goto done;
    335 		fmt++;		/* skip over '%' */
    336 
    337 		flags = 0;
    338 		dprec = 0;
    339 		width = 0;
    340 		prec = -1;
    341 		sign = '\0';
    342 
    343 rflag:		ch = *fmt++;
    344 reswitch:	switch (ch) {
    345 		case ' ':
    346 			/*
    347 			 * ``If the space and + flags both appear, the space
    348 			 * flag will be ignored.''
    349 			 *	-- ANSI X3J11
    350 			 */
    351 			if (!sign)
    352 				sign = ' ';
    353 			goto rflag;
    354 		case '#':
    355 			flags |= ALT;
    356 			goto rflag;
    357 		case '*':
    358 			/*
    359 			 * ``A negative field width argument is taken as a
    360 			 * - flag followed by a positive field width.''
    361 			 *	-- ANSI X3J11
    362 			 * They don't exclude field widths read from args.
    363 			 */
    364 			if ((width = va_arg(ap, int)) >= 0)
    365 				goto rflag;
    366 			width = -width;
    367 			/* FALLTHROUGH */
    368 		case '-':
    369 			flags |= LADJUST;
    370 			goto rflag;
    371 		case '+':
    372 			sign = '+';
    373 			goto rflag;
    374 		case '.':
    375 			if ((ch = *fmt++) == '*') {
    376 				n = va_arg(ap, int);
    377 				prec = n < 0 ? -1 : n;
    378 				goto rflag;
    379 			}
    380 			n = 0;
    381 			while (is_digit(ch)) {
    382 				n = 10 * n + to_digit(ch);
    383 				ch = *fmt++;
    384 			}
    385 			prec = n < 0 ? -1 : n;
    386 			goto reswitch;
    387 		case '0':
    388 			/*
    389 			 * ``Note that 0 is taken as a flag, not as the
    390 			 * beginning of a field width.''
    391 			 *	-- ANSI X3J11
    392 			 */
    393 			flags |= ZEROPAD;
    394 			goto rflag;
    395 		case '1': case '2': case '3': case '4':
    396 		case '5': case '6': case '7': case '8': case '9':
    397 			n = 0;
    398 			do {
    399 				n = 10 * n + to_digit(ch);
    400 				ch = *fmt++;
    401 			} while (is_digit(ch));
    402 			width = n;
    403 			goto reswitch;
    404 #ifdef FLOATING_POINT
    405 		case 'L':
    406 			flags |= LONGDBL;
    407 			goto rflag;
    408 #endif
    409 		case 'h':
    410 			flags |= SHORTINT;
    411 			goto rflag;
    412 		case 'l':
    413 			if (*fmt == 'l') {
    414 				fmt++;
    415 				flags |= QUADINT;
    416 			} else {
    417 				flags |= LONGINT;
    418 			}
    419 			goto rflag;
    420 		case 'q':
    421 			flags |= QUADINT;
    422 			goto rflag;
    423 		case 'c':
    424 			*buf = va_arg(ap, int);
    425 			cp = buf;
    426 			size = 1;
    427 			sign = '\0';
    428 			break;
    429 		case 'D':
    430 			flags |= LONGINT;
    431 			/*FALLTHROUGH*/
    432 		case 'd':
    433 		case 'i':
    434 			_uquad = SARG();
    435 			if ((quad_t)_uquad < 0) {
    436 				_uquad = -_uquad;
    437 				sign = '-';
    438 			}
    439 			base = DEC;
    440 			goto number;
    441 #ifdef FLOATING_POINT
    442 		case 'e':
    443 		case 'E':
    444 		case 'f':
    445 		case 'g':
    446 		case 'G':
    447 			if (prec == -1) {
    448 				prec = DEFPREC;
    449 			} else if ((ch == 'g' || ch == 'G') && prec == 0) {
    450 				prec = 1;
    451 			}
    452 
    453 			if (flags & LONGDBL) {
    454 				_double = (double) va_arg(ap, long double);
    455 			} else {
    456 				_double = va_arg(ap, double);
    457 			}
    458 
    459 			/* do this before tricky precision changes */
    460 			if (isinf(_double)) {
    461 				if (_double < 0)
    462 					sign = '-';
    463 				cp = "Inf";
    464 				size = 3;
    465 				break;
    466 			}
    467 			if (isnan(_double)) {
    468 				cp = "NaN";
    469 				size = 3;
    470 				break;
    471 			}
    472 
    473 			flags |= FPT;
    474 			cp = cvt(_double, prec, flags, &softsign,
    475 				&expt, ch, &ndig);
    476 			if (ch == 'g' || ch == 'G') {
    477 				if (expt <= -4 || expt > prec)
    478 					ch = (ch == 'g') ? 'e' : 'E';
    479 				else
    480 					ch = 'g';
    481 			}
    482 			if (ch <= 'e') {	/* 'e' or 'E' fmt */
    483 				--expt;
    484 				expsize = exponent(expstr, expt, ch);
    485 				size = expsize + ndig;
    486 				if (ndig > 1 || flags & ALT)
    487 					++size;
    488 			} else if (ch == 'f') {		/* f fmt */
    489 				if (expt > 0) {
    490 					size = expt;
    491 					if (prec || flags & ALT)
    492 						size += prec + 1;
    493 				} else	/* "0.X" */
    494 					size = prec + 2;
    495 			} else if (expt >= ndig) {	/* fixed g fmt */
    496 				size = expt;
    497 				if (flags & ALT)
    498 					++size;
    499 			} else
    500 				size = ndig + (expt > 0 ?
    501 					1 : 2 - expt);
    502 
    503 			if (softsign)
    504 				sign = '-';
    505 			break;
    506 #endif /* FLOATING_POINT */
    507 		case 'n':
    508 			if (flags & QUADINT)
    509 				*va_arg(ap, quad_t *) = ret;
    510 			else if (flags & LONGINT)
    511 				*va_arg(ap, long *) = ret;
    512 			else if (flags & SHORTINT)
    513 				*va_arg(ap, short *) = ret;
    514 			else
    515 				*va_arg(ap, int *) = ret;
    516 			continue;	/* no output */
    517 		case 'O':
    518 			flags |= LONGINT;
    519 			/*FALLTHROUGH*/
    520 		case 'o':
    521 			_uquad = UARG();
    522 			base = OCT;
    523 			goto nosign;
    524 		case 'p':
    525 			/*
    526 			 * ``The argument shall be a pointer to void.  The
    527 			 * value of the pointer is converted to a sequence
    528 			 * of printable characters, in an implementation-
    529 			 * defined manner.''
    530 			 *	-- ANSI X3J11
    531 			 */
    532 			/* NOSTRICT */
    533 			_uquad = (u_long)va_arg(ap, void *);
    534 			base = HEX;
    535 			xdigs = "0123456789abcdef";
    536 			flags |= HEXPREFIX;
    537 			ch = 'x';
    538 			goto nosign;
    539 		case 's':
    540 			if ((cp = va_arg(ap, char *)) == NULL)
    541 				cp = "(null)";
    542 			if (prec >= 0) {
    543 				/*
    544 				 * can't use strlen; can only look for the
    545 				 * NUL in the first `prec' characters, and
    546 				 * strlen() will go further.
    547 				 */
    548 				char *p = memchr(cp, 0, (size_t)prec);
    549 
    550 				if (p != NULL) {
    551 					size = p - cp;
    552 					if (size > prec)
    553 						size = prec;
    554 				} else
    555 					size = prec;
    556 			} else
    557 				size = strlen(cp);
    558 			sign = '\0';
    559 			break;
    560 		case 'U':
    561 			flags |= LONGINT;
    562 			/*FALLTHROUGH*/
    563 		case 'u':
    564 			_uquad = UARG();
    565 			base = DEC;
    566 			goto nosign;
    567 		case 'X':
    568 			xdigs = "0123456789ABCDEF";
    569 			goto hex;
    570 		case 'x':
    571 			xdigs = "0123456789abcdef";
    572 hex:			_uquad = UARG();
    573 			base = HEX;
    574 			/* leading 0x/X only if non-zero */
    575 			if (flags & ALT && _uquad != 0)
    576 				flags |= HEXPREFIX;
    577 
    578 			/* unsigned conversions */
    579 nosign:			sign = '\0';
    580 			/*
    581 			 * ``... diouXx conversions ... if a precision is
    582 			 * specified, the 0 flag will be ignored.''
    583 			 *	-- ANSI X3J11
    584 			 */
    585 number:			if ((dprec = prec) >= 0)
    586 				flags &= ~ZEROPAD;
    587 
    588 			/*
    589 			 * ``The result of converting a zero value with an
    590 			 * explicit precision of zero is no characters.''
    591 			 *	-- ANSI X3J11
    592 			 */
    593 			bp = buf + BUF;
    594 			if (_uquad != 0 || prec != 0) {
    595 				/*
    596 				 * Unsigned mod is hard, and unsigned mod
    597 				 * by a constant is easier than that by
    598 				 * a variable; hence this switch.
    599 				 */
    600 				switch (base) {
    601 				case OCT:
    602 					do {
    603 						*--bp = to_char(_uquad & 7);
    604 						_uquad >>= 3;
    605 					} while (_uquad);
    606 					/* handle octal leading 0 */
    607 					if (flags & ALT && *bp != '0')
    608 						*--bp = '0';
    609 					break;
    610 
    611 				case DEC:
    612 					/* many numbers are 1 digit */
    613 					while (_uquad >= 10) {
    614 						*--bp = to_char(_uquad % 10);
    615 						_uquad /= 10;
    616 					}
    617 					*--bp = to_char(_uquad);
    618 					break;
    619 
    620 				case HEX:
    621 					do {
    622 						*--bp = xdigs[(size_t)
    623 						    (_uquad & 15)];
    624 						_uquad >>= 4;
    625 					} while (_uquad);
    626 					break;
    627 
    628 				default:
    629 					cp = "bug in vfprintf: bad base";
    630 					size = strlen(cp);
    631 					goto skipsize;
    632 				}
    633 			}
    634 			cp = bp;
    635 			size = buf + BUF - bp;
    636 		skipsize:
    637 			break;
    638 		default:	/* "%?" prints ?, unless ? is NUL */
    639 			if (ch == '\0')
    640 				goto done;
    641 			/* pretend it was %c with argument ch */
    642 			*buf = ch;
    643 			cp = buf;
    644 			size = 1;
    645 			sign = '\0';
    646 			break;
    647 		}
    648 
    649 		/*
    650 		 * All reasonable formats wind up here.  At this point, `cp'
    651 		 * points to a string which (if not flags&LADJUST) should be
    652 		 * padded out to `width' places.  If flags&ZEROPAD, it should
    653 		 * first be prefixed by any sign or other prefix; otherwise,
    654 		 * it should be blank padded before the prefix is emitted.
    655 		 * After any left-hand padding and prefixing, emit zeroes
    656 		 * required by a decimal [diouxX] precision, then print the
    657 		 * string proper, then emit zeroes required by any leftover
    658 		 * floating precision; finally, if LADJUST, pad with blanks.
    659 		 *
    660 		 * Compute actual size, so we know how much to pad.
    661 		 * size excludes decimal prec; realsz includes it.
    662 		 */
    663 		realsz = dprec > size ? dprec : size;
    664 		if (sign)
    665 			realsz++;
    666 		else if (flags & HEXPREFIX)
    667 			realsz+= 2;
    668 
    669 		/* right-adjusting blank padding */
    670 		if ((flags & (LADJUST|ZEROPAD)) == 0)
    671 			PAD(width - realsz, blanks);
    672 
    673 		/* prefix */
    674 		if (sign) {
    675 			PRINT(&sign, 1);
    676 		} else if (flags & HEXPREFIX) {
    677 			ox[0] = '0';
    678 			ox[1] = ch;
    679 			PRINT(ox, 2);
    680 		}
    681 
    682 		/* right-adjusting zero padding */
    683 		if ((flags & (LADJUST|ZEROPAD)) == ZEROPAD)
    684 			PAD(width - realsz, zeroes);
    685 
    686 		/* leading zeroes from decimal precision */
    687 		PAD(dprec - size, zeroes);
    688 
    689 		/* the string or number proper */
    690 #ifdef FLOATING_POINT
    691 		if ((flags & FPT) == 0) {
    692 			PRINT(cp, size);
    693 		} else {	/* glue together f_p fragments */
    694 			if (ch >= 'f') {	/* 'f' or 'g' */
    695 				if (_double == 0) {
    696 					/* kludge for __dtoa irregularity */
    697 					PRINT("0", 1);
    698 					if (expt < ndig || (flags & ALT) != 0) {
    699 						PRINT(decimal_point, 1);
    700 						PAD(ndig - 1, zeroes);
    701 					}
    702 				} else if (expt <= 0) {
    703 					PRINT("0", 1);
    704 					PRINT(decimal_point, 1);
    705 					PAD(-expt, zeroes);
    706 					PRINT(cp, ndig);
    707 				} else if (expt >= ndig) {
    708 					PRINT(cp, ndig);
    709 					PAD(expt - ndig, zeroes);
    710 					if (flags & ALT)
    711 						PRINT(".", 1);
    712 				} else {
    713 					PRINT(cp, expt);
    714 					cp += expt;
    715 					PRINT(".", 1);
    716 					PRINT(cp, ndig-expt);
    717 				}
    718 			} else {	/* 'e' or 'E' */
    719 				if (ndig > 1 || flags & ALT) {
    720 					ox[0] = *cp++;
    721 					ox[1] = '.';
    722 					PRINT(ox, 2);
    723 					if (_double) {
    724 						PRINT(cp, ndig-1);
    725 					} else	/* 0.[0..] */
    726 						/* __dtoa irregularity */
    727 						PAD(ndig - 1, zeroes);
    728 				} else	/* XeYYY */
    729 					PRINT(cp, 1);
    730 				PRINT(expstr, expsize);
    731 			}
    732 		}
    733 #else
    734 		PRINT(cp, size);
    735 #endif
    736 		/* left-adjusting padding (always blank) */
    737 		if (flags & LADJUST)
    738 			PAD(width - realsz, blanks);
    739 
    740 		/* finally, adjust ret */
    741 		ret += width > realsz ? width : realsz;
    742 
    743 		FLUSH();	/* copy out the I/O vectors */
    744 	}
    745 done:
    746 	FLUSH();
    747 error:
    748 	if (__sferror(fp))
    749 		ret = -1;
    750 	FUNLOCKFILE(fp);
    751 	return (ret);
    752 }
    753 
    754 #ifdef FLOATING_POINT
    755 
    756 static char *
    757 cvt(value, ndigits, flags, sign, decpt, ch, length)
    758 	double value;
    759 	int ndigits, flags, *decpt, ch, *length;
    760 	char *sign;
    761 {
    762 	int mode, dsgn;
    763 	char *digits, *bp, *rve;
    764 
    765 	_DIAGASSERT(decpt != NULL);
    766 	_DIAGASSERT(length != NULL);
    767 	_DIAGASSERT(sign != NULL);
    768 
    769 	if (ch == 'f') {
    770 		mode = 3;		/* ndigits after the decimal point */
    771 	} else {
    772 		/* To obtain ndigits after the decimal point for the 'e'
    773 		 * and 'E' formats, round to ndigits + 1 significant
    774 		 * figures.
    775 		 */
    776 		if (ch == 'e' || ch == 'E') {
    777 			ndigits++;
    778 		}
    779 		mode = 2;		/* ndigits significant digits */
    780 	}
    781 
    782 	if (value < 0) {
    783 		value = -value;
    784 		*sign = '-';
    785 	} else
    786 		*sign = '\000';
    787 	digits = __dtoa(value, mode, ndigits, decpt, &dsgn, &rve);
    788 	if ((ch != 'g' && ch != 'G') || flags & ALT) {	/* Print trailing zeros */
    789 		bp = digits + ndigits;
    790 		if (ch == 'f') {
    791 			if (*digits == '0' && value)
    792 				*decpt = -ndigits + 1;
    793 			bp += *decpt;
    794 		}
    795 		if (value == 0)	/* kludge for __dtoa irregularity */
    796 			rve = bp;
    797 		while (rve < bp)
    798 			*rve++ = '0';
    799 	}
    800 	*length = rve - digits;
    801 	return (digits);
    802 }
    803 
    804 static int
    805 exponent(p0, exp, fmtch)
    806 	char *p0;
    807 	int exp, fmtch;
    808 {
    809 	char *p, *t;
    810 	char expbuf[MAXEXP];
    811 
    812 	_DIAGASSERT(p0 != NULL);
    813 
    814 	p = p0;
    815 	*p++ = fmtch;
    816 	if (exp < 0) {
    817 		exp = -exp;
    818 		*p++ = '-';
    819 	}
    820 	else
    821 		*p++ = '+';
    822 	t = expbuf + MAXEXP;
    823 	if (exp > 9) {
    824 		do {
    825 			*--t = to_char(exp % 10);
    826 		} while ((exp /= 10) > 9);
    827 		*--t = to_char(exp);
    828 		for (; t < expbuf + MAXEXP; *p++ = *t++);
    829 	}
    830 	else {
    831 		*p++ = '0';
    832 		*p++ = to_char(exp);
    833 	}
    834 	return (p - p0);
    835 }
    836 #endif /* FLOATING_POINT */
    837