add %f to printf
authorLaurent Mazet <mazet@softndesign.org>
Sat, 24 Dec 2022 08:17:36 +0000 (09:17 +0100)
committerLaurent Mazet <mazet@softndesign.org>
Sat, 24 Dec 2022 08:17:36 +0000 (09:17 +0100)
fdprintf.c

index 58bf89d8449c0a8f3f5e02c71834afd648b6f2e1..1bc1b1907a0de6f82d320a015d562131c39cb7ad 100644 (file)
@@ -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';