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