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