vfprintf.c revision 1.2 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[] = "@(#)vfprintf.c 5.47 (Berkeley) 3/22/91";
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 #include <math.h>
49 #include <stdio.h>
50 #include <string.h>
51 #if __STDC__
52 #include <stdarg.h>
53 #else
54 #include <varargs.h>
55 #endif
56 #include "local.h"
57 #include "fvwrite.h"
58
59 /*
60 * Define FLOATING_POINT to get floating point.
61 * Define CSH to get a csh-specific version (grr).
62 */
63 #ifndef CSH
64 #define FLOATING_POINT
65 #endif
66
67 /* end of configuration stuff */
68
69
70 #ifdef CSH
71 /*
72 * C shell hacks. Ick, gag.
73 */
74 #undef BUFSIZ
75 #include "sh.h"
76
77 #if __STDC__
78 int
79 printf(const char *fmt, ...) {
80 FILE f;
81 va_list ap;
82 int ret;
83
84 va_start(ap, fmt);
85 f._flags = __SWR;
86 f._write = NULL;
87 ret = vfprintf(&f, fmt, ap);
88 va_end(ap);
89 return ret;
90 }
91 #else
92 int
93 printf(fmt, args)
94 char *fmt;
95 {
96 FILE f;
97
98 f._flags = __SWR;
99 f._write = NULL;
100 return (vfprintf(&f, fmt, &args));
101 }
102 #endif
103
104 int
105 __sprint(fp, uio)
106 FILE *fp;
107 register struct __suio *uio;
108 {
109 register char *p;
110 register int n, ch, iovcnt;
111 register struct __siov *iov;
112
113 /* must allow sprintf to work, might as well allow others too */
114 if (fp->_write || fp->_flags & __SSTR) {
115 if (uio->uio_resid == 0) {
116 uio->uio_iovcnt = 0;
117 return (0);
118 }
119 n = __sfvwrite(fp, uio);
120 uio->uio_resid = 0;
121 uio->uio_iovcnt = 0;
122 return (n);
123 }
124 iov = uio->uio_iov;
125 for (iovcnt = uio->uio_iovcnt; --iovcnt >= 0; iov++) {
126 for (p = iov->iov_base, n = iov->iov_len; --n >= 0;) {
127 #ifdef CSHPUTCHAR
128 ch = *p++;
129 CSHPUTCHAR; /* this horrid macro uses `ch' */
130 #else
131 #undef putchar
132 putchar(*p++);
133 #endif
134 }
135 }
136 uio->uio_resid = 0;
137 uio->uio_iovcnt = 0;
138 return (0);
139 }
140
141 #else /* CSH */
142
143 /*
144 * Flush out all the vectors defined by the given uio,
145 * then reset it so that it can be reused.
146 */
147 static int
148 __sprint(fp, uio)
149 FILE *fp;
150 register struct __suio *uio;
151 {
152 register int err;
153
154 if (uio->uio_resid == 0) {
155 uio->uio_iovcnt = 0;
156 return (0);
157 }
158 err = __sfvwrite(fp, uio);
159 uio->uio_resid = 0;
160 uio->uio_iovcnt = 0;
161 return (err);
162 }
163
164 /*
165 * Helper function for `fprintf to unbuffered unix file': creates a
166 * temporary buffer. We only work on write-only files; this avoids
167 * worries about ungetc buffers and so forth.
168 */
169 static int
170 __sbprintf(fp, fmt, ap)
171 register FILE *fp;
172 const char *fmt;
173 va_list ap;
174 {
175 int ret;
176 FILE fake;
177 unsigned char buf[BUFSIZ];
178
179 /* copy the important variables */
180 fake._flags = fp->_flags & ~__SNBF;
181 fake._file = fp->_file;
182 fake._cookie = fp->_cookie;
183 fake._write = fp->_write;
184
185 /* set up the buffer */
186 fake._bf._base = fake._p = buf;
187 fake._bf._size = fake._w = sizeof(buf);
188 fake._lbfsize = 0; /* not actually used, but Just In Case */
189
190 /* do the work, then copy any error status */
191 ret = vfprintf(&fake, fmt, ap);
192 if (ret >= 0 && fflush(&fake))
193 ret = EOF;
194 if (fake._flags & __SERR)
195 fp->_flags |= __SERR;
196 return (ret);
197 }
198
199 #endif /* CSH */
200
201
202 #ifdef FLOATING_POINT
203 #include "floatio.h"
204
205 #define BUF (MAXEXP+MAXFRACT+1) /* + decimal point */
206 #define DEFPREC 6
207
208 static int cvt();
209
210 #else /* no FLOATING_POINT */
211
212 #define BUF 40
213
214 #endif /* FLOATING_POINT */
215
216
217 /*
218 * Macros for converting digits to letters and vice versa
219 */
220 #define to_digit(c) ((c) - '0')
221 #define is_digit(c) ((unsigned)to_digit(c) <= 9)
222 #define to_char(n) ((n) + '0')
223
224 /*
225 * Flags used during conversion.
226 */
227 #define LONGINT 0x01 /* long integer */
228 #define LONGDBL 0x02 /* long double; unimplemented */
229 #define SHORTINT 0x04 /* short integer */
230 #define ALT 0x08 /* alternate form */
231 #define LADJUST 0x10 /* left adjustment */
232 #define ZEROPAD 0x20 /* zero (as opposed to blank) pad */
233 #define HEXPREFIX 0x40 /* add 0x or 0X prefix */
234
235 int
236 vfprintf(fp, fmt0, ap)
237 FILE *fp;
238 const char *fmt0;
239 #if tahoe
240 register /* technically illegal, since we do not know what type va_list is */
241 #endif
242 _VA_LIST_ ap;
243 {
244 register char *fmt; /* format string */
245 register int ch; /* character from fmt */
246 register int n; /* handy integer (short term usage) */
247 register char *cp; /* handy char pointer (short term usage) */
248 register struct __siov *iovp;/* for PRINT macro */
249 register int flags; /* flags as above */
250 int ret; /* return value accumulator */
251 int width; /* width from format (%8d), or 0 */
252 int prec; /* precision from format (%.3d), or -1 */
253 char sign; /* sign prefix (' ', '+', '-', or \0) */
254 #ifdef FLOATING_POINT
255 char softsign; /* temporary negative sign for floats */
256 double _double; /* double precision arguments %[eEfgG] */
257 int fpprec; /* `extra' floating precision in [eEfgG] */
258 #endif
259 u_long _ulong; /* integer arguments %[diouxX] */
260 enum { OCT, DEC, HEX } base;/* base for [diouxX] conversion */
261 int dprec; /* a copy of prec if [diouxX], 0 otherwise */
262 int fieldsz; /* field size expanded by sign, etc */
263 int realsz; /* field size expanded by dprec */
264 int size; /* size of converted field or string */
265 char *xdigs; /* digits for [xX] conversion */
266 #define NIOV 8
267 struct __suio uio; /* output information: summary */
268 struct __siov iov[NIOV];/* ... and individual io vectors */
269 char buf[BUF]; /* space for %c, %[diouxX], %[eEfgG] */
270 char ox[2]; /* space for 0x hex-prefix */
271
272 /*
273 * Choose PADSIZE to trade efficiency vs size. If larger
274 * printf fields occur frequently, increase PADSIZE (and make
275 * the initialisers below longer).
276 */
277 #define PADSIZE 16 /* pad chunk size */
278 static char blanks[PADSIZE] =
279 {' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' '};
280 static char zeroes[PADSIZE] =
281 {'0','0','0','0','0','0','0','0','0','0','0','0','0','0','0','0'};
282
283 #if __STDC__
284 va_start (ap, fmt);
285 #endif
286
287 /*
288 * BEWARE, these `goto error' on error, and PAD uses `n'.
289 */
290 #define PRINT(ptr, len) { \
291 iovp->iov_base = (ptr); \
292 iovp->iov_len = (len); \
293 uio.uio_resid += (len); \
294 iovp++; \
295 if (++uio.uio_iovcnt >= NIOV) { \
296 if (__sprint(fp, &uio)) \
297 goto error; \
298 iovp = iov; \
299 } \
300 }
301 #define PAD(howmany, with) { \
302 if ((n = (howmany)) > 0) { \
303 while (n > PADSIZE) { \
304 PRINT(with, PADSIZE); \
305 n -= PADSIZE; \
306 } \
307 PRINT(with, n); \
308 } \
309 }
310 #define FLUSH() { \
311 if (uio.uio_resid && __sprint(fp, &uio)) \
312 goto error; \
313 uio.uio_iovcnt = 0; \
314 iovp = iov; \
315 }
316
317 /*
318 * To extend shorts properly, we need both signed and unsigned
319 * argument extraction methods.
320 */
321 #define SARG() \
322 (flags&LONGINT ? va_arg(ap, long) : \
323 flags&SHORTINT ? (long)(short)va_arg(ap, int) : \
324 (long)va_arg(ap, int))
325 #define UARG() \
326 (flags&LONGINT ? va_arg(ap, u_long) : \
327 flags&SHORTINT ? (u_long)(u_short)va_arg(ap, int) : \
328 (u_long)va_arg(ap, u_int))
329
330 #ifndef CSH
331 /* sorry, fprintf(read_only_file, "") returns EOF, not 0 */
332 if (cantwrite(fp))
333 return (EOF);
334
335 /* optimise fprintf(stderr) (and other unbuffered Unix files) */
336 if ((fp->_flags & (__SNBF|__SWR|__SRW)) == (__SNBF|__SWR) &&
337 fp->_file >= 0)
338 return (__sbprintf(fp, fmt0, ap));
339 #endif /* CSH */
340
341 fmt = (char *)fmt0;
342 uio.uio_iov = iovp = iov;
343 uio.uio_resid = 0;
344 uio.uio_iovcnt = 0;
345 ret = 0;
346
347 /*
348 * Scan the format for conversions (`%' character).
349 */
350 for (;;) {
351 for (cp = fmt; (ch = *fmt) != '\0' && ch != '%'; fmt++)
352 /* void */;
353 if ((n = fmt - cp) != 0) {
354 PRINT(cp, n);
355 ret += n;
356 }
357 if (ch == '\0')
358 goto done;
359 fmt++; /* skip over '%' */
360
361 flags = 0;
362 dprec = 0;
363 #ifdef FLOATING_POINT
364 fpprec = 0;
365 #endif
366 width = 0;
367 prec = -1;
368 sign = '\0';
369
370 rflag: ch = *fmt++;
371 reswitch: switch (ch) {
372 case ' ':
373 /*
374 * ``If the space and + flags both appear, the space
375 * flag will be ignored.''
376 * -- ANSI X3J11
377 */
378 if (!sign)
379 sign = ' ';
380 goto rflag;
381 case '#':
382 flags |= ALT;
383 goto rflag;
384 case '*':
385 /*
386 * ``A negative field width argument is taken as a
387 * - flag followed by a positive field width.''
388 * -- ANSI X3J11
389 * They don't exclude field widths read from args.
390 */
391 if ((width = va_arg(ap, int)) >= 0)
392 goto rflag;
393 width = -width;
394 /* FALLTHROUGH */
395 case '-':
396 flags |= LADJUST;
397 goto rflag;
398 case '+':
399 sign = '+';
400 goto rflag;
401 case '.':
402 if ((ch = *fmt++) == '*') {
403 n = va_arg(ap, int);
404 prec = n < 0 ? -1 : n;
405 goto rflag;
406 }
407 n = 0;
408 while (is_digit(ch)) {
409 n = 10 * n + to_digit(ch);
410 ch = *fmt++;
411 }
412 prec = n < 0 ? -1 : n;
413 goto reswitch;
414 case '0':
415 /*
416 * ``Note that 0 is taken as a flag, not as the
417 * beginning of a field width.''
418 * -- ANSI X3J11
419 */
420 flags |= ZEROPAD;
421 goto rflag;
422 case '1': case '2': case '3': case '4':
423 case '5': case '6': case '7': case '8': case '9':
424 n = 0;
425 do {
426 n = 10 * n + to_digit(ch);
427 ch = *fmt++;
428 } while (is_digit(ch));
429 width = n;
430 goto reswitch;
431 #ifdef FLOATING_POINT
432 case 'L':
433 flags |= LONGDBL;
434 goto rflag;
435 #endif
436 case 'h':
437 flags |= SHORTINT;
438 goto rflag;
439 case 'l':
440 flags |= LONGINT;
441 goto rflag;
442 case 'c':
443 *(cp = buf) = va_arg(ap, int);
444 size = 1;
445 sign = '\0';
446 break;
447 case 'D':
448 flags |= LONGINT;
449 /*FALLTHROUGH*/
450 case 'd':
451 case 'i':
452 _ulong = SARG();
453 if ((long)_ulong < 0) {
454 _ulong = -_ulong;
455 sign = '-';
456 }
457 base = DEC;
458 goto number;
459 #ifdef FLOATING_POINT
460 case 'e':
461 case 'E':
462 case 'f':
463 case 'g':
464 case 'G':
465 _double = va_arg(ap, double);
466 /* do this before tricky precision changes */
467 if (isinf(_double)) {
468 if (_double < 0)
469 sign = '-';
470 cp = "Inf";
471 size = 3;
472 break;
473 }
474 if (isnan(_double)) {
475 cp = "NaN";
476 size = 3;
477 break;
478 }
479 /*
480 * don't do unrealistic precision; just pad it with
481 * zeroes later, so buffer size stays rational.
482 */
483 if (prec > MAXFRACT) {
484 if (ch != 'g' && ch != 'G' || (flags&ALT))
485 fpprec = prec - MAXFRACT;
486 prec = MAXFRACT;
487 } else if (prec == -1)
488 prec = DEFPREC;
489 /*
490 * cvt may have to round up before the "start" of
491 * its buffer, i.e. ``intf("%.2f", (double)9.999);'';
492 * if the first character is still NUL, it did.
493 * softsign avoids negative 0 if _double < 0 but
494 * no significant digits will be shown.
495 */
496 cp = buf;
497 *cp = '\0';
498 size = cvt(_double, prec, flags, &softsign, ch,
499 cp, buf + sizeof(buf));
500 if (softsign)
501 sign = '-';
502 if (*cp == '\0')
503 cp++;
504 break;
505 #endif /* FLOATING_POINT */
506 case 'n':
507 if (flags & LONGINT)
508 *va_arg(ap, long *) = ret;
509 else if (flags & SHORTINT)
510 *va_arg(ap, short *) = ret;
511 else
512 *va_arg(ap, int *) = ret;
513 continue; /* no output */
514 case 'O':
515 flags |= LONGINT;
516 /*FALLTHROUGH*/
517 case 'o':
518 _ulong = UARG();
519 base = OCT;
520 goto nosign;
521 case 'p':
522 /*
523 * ``The argument shall be a pointer to void. The
524 * value of the pointer is converted to a sequence
525 * of printable characters, in an implementation-
526 * defined manner.''
527 * -- ANSI X3J11
528 */
529 /* NOSTRICT */
530 _ulong = (u_long)va_arg(ap, void *);
531 base = HEX;
532 xdigs = "0123456789abcdef";
533 flags |= HEXPREFIX;
534 ch = 'x';
535 goto nosign;
536 case 's':
537 if ((cp = va_arg(ap, char *)) == NULL)
538 cp = "(null)";
539 if (prec >= 0) {
540 /*
541 * can't use strlen; can only look for the
542 * NUL in the first `prec' characters, and
543 * strlen() will go further.
544 */
545 char *p = memchr(cp, 0, prec);
546
547 if (p != NULL) {
548 size = p - cp;
549 if (size > prec)
550 size = prec;
551 } else
552 size = prec;
553 } else
554 size = strlen(cp);
555 sign = '\0';
556 break;
557 case 'U':
558 flags |= LONGINT;
559 /*FALLTHROUGH*/
560 case 'u':
561 _ulong = UARG();
562 base = DEC;
563 goto nosign;
564 case 'X':
565 xdigs = "0123456789ABCDEF";
566 goto hex;
567 case 'x':
568 xdigs = "0123456789abcdef";
569 hex: _ulong = UARG();
570 base = HEX;
571 /* leading 0x/X only if non-zero */
572 if (flags & ALT && _ulong != 0)
573 flags |= HEXPREFIX;
574
575 /* unsigned conversions */
576 nosign: sign = '\0';
577 /*
578 * ``... diouXx conversions ... if a precision is
579 * specified, the 0 flag will be ignored.''
580 * -- ANSI X3J11
581 */
582 number: if ((dprec = prec) >= 0)
583 flags &= ~ZEROPAD;
584
585 /*
586 * ``The result of converting a zero value with an
587 * explicit precision of zero is no characters.''
588 * -- ANSI X3J11
589 */
590 cp = buf + BUF;
591 if (_ulong != 0 || prec != 0) {
592 /*
593 * unsigned mod is hard, and unsigned mod
594 * by a constant is easier than that by
595 * a variable; hence this switch.
596 */
597 switch (base) {
598 case OCT:
599 do {
600 *--cp = to_char(_ulong & 7);
601 _ulong >>= 3;
602 } while (_ulong);
603 /* handle octal leading 0 */
604 if (flags & ALT && *cp != '0')
605 *--cp = '0';
606 break;
607
608 case DEC:
609 /* many numbers are 1 digit */
610 while (_ulong >= 10) {
611 *--cp = to_char(_ulong % 10);
612 _ulong /= 10;
613 }
614 *--cp = to_char(_ulong);
615 break;
616
617 case HEX:
618 do {
619 *--cp = xdigs[_ulong & 15];
620 _ulong >>= 4;
621 } while (_ulong);
622 break;
623
624 default:
625 cp = "bug in vfprintf: bad base";
626 size = strlen(cp);
627 goto skipsize;
628 }
629 }
630 size = buf + BUF - cp;
631 skipsize:
632 break;
633 default: /* "%?" prints ?, unless ? is NUL */
634 if (ch == '\0')
635 goto done;
636 /* pretend it was %c with argument ch */
637 cp = buf;
638 *cp = ch;
639 size = 1;
640 sign = '\0';
641 break;
642 }
643
644 /*
645 * All reasonable formats wind up here. At this point,
646 * `cp' points to a string which (if not flags&LADJUST)
647 * should be padded out to `width' places. If
648 * flags&ZEROPAD, it should first be prefixed by any
649 * sign or other prefix; otherwise, it should be blank
650 * padded before the prefix is emitted. After any
651 * left-hand padding and prefixing, emit zeroes
652 * required by a decimal [diouxX] precision, then print
653 * the string proper, then emit zeroes required by any
654 * leftover floating precision; finally, if LADJUST,
655 * pad with blanks.
656 */
657
658 /*
659 * compute actual size, so we know how much to pad.
660 * fieldsz excludes decimal prec; realsz includes it
661 */
662 #ifdef FLOATING_POINT
663 fieldsz = size + fpprec;
664 #else
665 fieldsz = size;
666 #endif
667 if (sign)
668 fieldsz++;
669 else if (flags & HEXPREFIX)
670 fieldsz += 2;
671 realsz = dprec > fieldsz ? dprec : fieldsz;
672
673 /* right-adjusting blank padding */
674 if ((flags & (LADJUST|ZEROPAD)) == 0)
675 PAD(width - realsz, blanks);
676
677 /* prefix */
678 if (sign) {
679 PRINT(&sign, 1);
680 } else if (flags & HEXPREFIX) {
681 ox[0] = '0';
682 ox[1] = ch;
683 PRINT(ox, 2);
684 }
685
686 /* right-adjusting zero padding */
687 if ((flags & (LADJUST|ZEROPAD)) == ZEROPAD)
688 PAD(width - realsz, zeroes);
689
690 /* leading zeroes from decimal precision */
691 PAD(dprec - fieldsz, zeroes);
692
693 /* the string or number proper */
694 PRINT(cp, size);
695
696 #ifdef FLOATING_POINT
697 /* trailing f.p. zeroes */
698 PAD(fpprec, zeroes);
699 #endif
700
701 /* left-adjusting padding (always blank) */
702 if (flags & LADJUST)
703 PAD(width - realsz, blanks);
704
705 /* finally, adjust ret */
706 ret += width > realsz ? width : realsz;
707
708 FLUSH(); /* copy out the I/O vectors */
709 }
710 done:
711 FLUSH();
712 error:
713 return (__sferror(fp) ? EOF : ret);
714 /* NOTREACHED */
715 }
716
717 #ifdef FLOATING_POINT
718 #include <math.h>
719
720 static char *exponent();
721 static char *round();
722
723 static int
724 cvt(number, prec, flags, signp, fmtch, startp, endp)
725 double number;
726 register int prec;
727 int flags;
728 char *signp;
729 int fmtch;
730 char *startp, *endp;
731 {
732 register char *p, *t;
733 register double fract;
734 int dotrim, expcnt, gformat;
735 double integer, tmp;
736
737 dotrim = expcnt = gformat = 0;
738 if (number < 0) {
739 number = -number;
740 *signp = '-';
741 } else
742 *signp = 0;
743
744 fract = modf(number, &integer);
745
746 /* get an extra slot for rounding. */
747 t = ++startp;
748
749 /*
750 * get integer portion of number; put into the end of the buffer; the
751 * .01 is added for modf(356.0 / 10, &integer) returning .59999999...
752 */
753 for (p = endp - 1; integer; ++expcnt) {
754 tmp = modf(integer / 10, &integer);
755 *p-- = to_char((int)((tmp + .01) * 10));
756 }
757 switch (fmtch) {
758 case 'f':
759 /* reverse integer into beginning of buffer */
760 if (expcnt)
761 for (; ++p < endp; *t++ = *p);
762 else
763 *t++ = '0';
764 /*
765 * if precision required or alternate flag set, add in a
766 * decimal point.
767 */
768 if (prec || flags&ALT)
769 *t++ = '.';
770 /* if requires more precision and some fraction left */
771 if (fract) {
772 if (prec)
773 do {
774 fract = modf(fract * 10, &tmp);
775 *t++ = to_char((int)tmp);
776 } while (--prec && fract);
777 if (fract)
778 startp = round(fract, (int *)NULL, startp,
779 t - 1, (char)0, signp);
780 }
781 for (; prec--; *t++ = '0');
782 break;
783 case 'e':
784 case 'E':
785 eformat: if (expcnt) {
786 *t++ = *++p;
787 if (prec || flags&ALT)
788 *t++ = '.';
789 /* if requires more precision and some integer left */
790 for (; prec && ++p < endp; --prec)
791 *t++ = *p;
792 /*
793 * if done precision and more of the integer component,
794 * round using it; adjust fract so we don't re-round
795 * later.
796 */
797 if (!prec && ++p < endp) {
798 fract = 0;
799 startp = round((double)0, &expcnt, startp,
800 t - 1, *p, signp);
801 }
802 /* adjust expcnt for digit in front of decimal */
803 --expcnt;
804 }
805 /* until first fractional digit, decrement exponent */
806 else if (fract) {
807 /* adjust expcnt for digit in front of decimal */
808 for (expcnt = -1;; --expcnt) {
809 fract = modf(fract * 10, &tmp);
810 if (tmp)
811 break;
812 }
813 *t++ = to_char((int)tmp);
814 if (prec || flags&ALT)
815 *t++ = '.';
816 }
817 else {
818 *t++ = '0';
819 if (prec || flags&ALT)
820 *t++ = '.';
821 }
822 /* if requires more precision and some fraction left */
823 if (fract) {
824 if (prec)
825 do {
826 fract = modf(fract * 10, &tmp);
827 *t++ = to_char((int)tmp);
828 } while (--prec && fract);
829 if (fract)
830 startp = round(fract, &expcnt, startp,
831 t - 1, (char)0, signp);
832 }
833 /* if requires more precision */
834 for (; prec--; *t++ = '0');
835
836 /* unless alternate flag, trim any g/G format trailing 0's */
837 if (gformat && !(flags&ALT)) {
838 while (t > startp && *--t == '0');
839 if (*t == '.')
840 --t;
841 ++t;
842 }
843 t = exponent(t, expcnt, fmtch);
844 break;
845 case 'g':
846 case 'G':
847 /* a precision of 0 is treated as a precision of 1. */
848 if (!prec)
849 ++prec;
850 /*
851 * ``The style used depends on the value converted; style e
852 * will be used only if the exponent resulting from the
853 * conversion is less than -4 or greater than the precision.''
854 * -- ANSI X3J11
855 */
856 if (expcnt > prec || !expcnt && fract && fract < .0001) {
857 /*
858 * g/G format counts "significant digits, not digits of
859 * precision; for the e/E format, this just causes an
860 * off-by-one problem, i.e. g/G considers the digit
861 * before the decimal point significant and e/E doesn't
862 * count it as precision.
863 */
864 --prec;
865 fmtch -= 2; /* G->E, g->e */
866 gformat = 1;
867 goto eformat;
868 }
869 /*
870 * reverse integer into beginning of buffer,
871 * note, decrement precision
872 */
873 if (expcnt)
874 for (; ++p < endp; *t++ = *p, --prec);
875 else
876 *t++ = '0';
877 /*
878 * if precision required or alternate flag set, add in a
879 * decimal point. If no digits yet, add in leading 0.
880 */
881 if (prec || flags&ALT) {
882 dotrim = 1;
883 *t++ = '.';
884 }
885 else
886 dotrim = 0;
887 /* if requires more precision and some fraction left */
888 if (fract) {
889 if (prec) {
890 do {
891 fract = modf(fract * 10, &tmp);
892 *t++ = to_char((int)tmp);
893 } while(!tmp);
894 while (--prec && fract) {
895 fract = modf(fract * 10, &tmp);
896 *t++ = to_char((int)tmp);
897 }
898 }
899 if (fract)
900 startp = round(fract, (int *)NULL, startp,
901 t - 1, (char)0, signp);
902 }
903 /* alternate format, adds 0's for precision, else trim 0's */
904 if (flags&ALT)
905 for (; prec--; *t++ = '0');
906 else if (dotrim) {
907 while (t > startp && *--t == '0');
908 if (*t != '.')
909 ++t;
910 }
911 }
912 return (t - startp);
913 }
914
915 static char *
916 round(fract, exp, start, end, ch, signp)
917 double fract;
918 int *exp;
919 register char *start, *end;
920 char ch, *signp;
921 {
922 double tmp;
923
924 if (fract)
925 (void)modf(fract * 10, &tmp);
926 else
927 tmp = to_digit(ch);
928 if (tmp > 4)
929 for (;; --end) {
930 if (*end == '.')
931 --end;
932 if (++*end <= '9')
933 break;
934 *end = '0';
935 if (end == start) {
936 if (exp) { /* e/E; increment exponent */
937 *end = '1';
938 ++*exp;
939 }
940 else { /* f; add extra digit */
941 *--end = '1';
942 --start;
943 }
944 break;
945 }
946 }
947 /* ``"%.3f", (double)-0.0004'' gives you a negative 0. */
948 else if (*signp == '-')
949 for (;; --end) {
950 if (*end == '.')
951 --end;
952 if (*end != '0')
953 break;
954 if (end == start)
955 *signp = 0;
956 }
957 return (start);
958 }
959
960 static char *
961 exponent(p, exp, fmtch)
962 register char *p;
963 register int exp;
964 int fmtch;
965 {
966 register char *t;
967 char expbuf[MAXEXP];
968
969 *p++ = fmtch;
970 if (exp < 0) {
971 exp = -exp;
972 *p++ = '-';
973 }
974 else
975 *p++ = '+';
976 t = expbuf + MAXEXP;
977 if (exp > 9) {
978 do {
979 *--t = to_char(exp % 10);
980 } while ((exp /= 10) > 9);
981 *--t = to_char(exp);
982 for (; t < expbuf + MAXEXP; *p++ = *t++);
983 }
984 else {
985 *p++ = '0';
986 *p++ = to_char(exp);
987 }
988 return (p);
989 }
990 #endif /* FLOATING_POINT */
991