From 95834c7b69cecdc08bb2c7060d6b164513436274 Mon Sep 17 00:00:00 2001 From: Laurent Mazet Date: Sat, 24 Dec 2022 09:17:36 +0100 Subject: [PATCH] add %f to printf --- fdprintf.c | 57 ++++++++++++++++++++++++++++++++++++++++++++++++------ 1 file changed, 51 insertions(+), 6 deletions(-) diff --git a/fdprintf.c b/fdprintf.c index 58bf89d..1bc1b19 100644 --- a/fdprintf.c +++ b/fdprintf.c @@ -30,6 +30,19 @@ unsigned int nextpow (unsigned int x, int base) { return (n == 0) ? 1 : n; } +char *itoa (char *str, unsigned u, unsigned int sz) +{ + unsigned int i = (sz == 0 ) ? nextpow (u, 10) : sz; + char *s = str; + while (i > 0) { + str[i - 1] = '0' + (u % 10); + u /= 10; + i--; + s++; + } + return s; +} + /* simple fprintf function */ int fdprintf (int fd, const char *fmt, ...) @@ -41,6 +54,7 @@ int fdprintf (int fd, const char *fmt, ...) va_start (ap, fmt); while (*fmt) { char *s; + double f = 0.0; int d = 0; unsigned int u; char c = *fmt++; @@ -50,7 +64,7 @@ int fdprintf (int fd, const char *fmt, ...) *str++ = c; } else { int t = 0; - char w = '0'; + char w = '0'; int i, sz = 0; void *p = NULL; @@ -79,12 +93,43 @@ int fdprintf (int fd, const char *fmt, ...) t = 1; /* fall through */ case 'u': /* unsigned int */ - u = (t) ? (unsigned int)d : va_arg (ap, unsigned int); - for (i = nextpow (u, 10), s = str; i > 0; i--, s++) { - str[i - 1] = '0' + (u % 10); - u /= 10; + str = itoa (str, (t) ? (unsigned int)d : va_arg (ap, unsigned int), 0); + break; + case 'f': /* float */ + f = va_arg (ap, double); + if (f < 0) { + *str++ = '-'; + f = -f; + } + t = 0; + while (f > 10) { + f /= 10; + t++; + } + while (f < 1) { + f *= 10; + t--; + } + f += 1e-7; + if (f >= 10) { + f /= 10; + t++; + } + u = (int)f; + str = itoa (str, u, 0); + d = (int)((f - u) * 1e6); + if (d > 0) { + *str++ = '.'; + str = itoa (str, d, 6); + } + if (t != 0) { + *str++ = 'e'; + if (t < 0) { + *str++ = '-'; + t = -t; + } + str = itoa (str, t, 0); } - str = s; break; case 'p': /* pointer */ *str++ = '0'; -- 2.30.2