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