myprintf.c
changeset 60 47c13ca8c4d0
parent 58 9609c54a54d3
child 62 b7061c0e239f
--- a/myprintf.c
+++ b/myprintf.c
@@ -8,17 +8,23 @@
 #include <stdarg.h>
 #include <string.h>
 
+#define BUF_SIZE 1024
+
 int myprintf (char *fmt, ...)
 {
-    int i, pos = 0;
+    int i, value, pos = 0, size = 1;
+    char c;
+
+    char *ptr;
+    char *s;
+    char *s_str;
+    char v_str[28];
+
     va_list list;
 
-    char c;
-    char *s;
-    char s_str[1024];
-
-    char v[12];
-    int value;
+    if ((s_str = malloc (BUF_SIZE)) == NULL) {
+        return EOF;
+    }
 
     va_start (list, fmt);
 
@@ -29,35 +35,54 @@
             case 'c':
                 c = va_arg (list, int);
                 s_str[pos++] = c;
-                c = *fmt++;
                 break;
+
             case 's':
                 s = va_arg (list, char *);
+                while ((pos + strlen (s)) > (size * BUF_SIZE)) {
+                    if ((ptr = realloc (s_str, ++size * BUF_SIZE)) == NULL) {
+                        s_str[pos] = '\0';
+                        fputs (s_str, stdout);  /* print it anyway... */
+                        return EOF;
+                    }
+                    s_str = ptr;
+                }
                 for (i = 0; i < strlen (s); i++) {
                     s_str[pos++] = s[i];
                 }
-                c = *fmt++;
                 break;
+
             case 'd':
                 value = va_arg (list, int);
-                sprintf (v, "%d", value);
-                for (i = 0; i < strlen (v); i++) {
-                    s_str[pos++] = v[i];
+                sprintf (v_str, "%d", value);
+                for (i = 0; i < strlen (v_str); i++) {
+                    s_str[pos++] = v_str[i];
                 }
-                c = *fmt++;
                 break;
+
             default:
-                puts ("Unknown character");
+                s_str[pos++] = *fmt;
             }
+
+            c = *fmt++;
         default:
             s_str[pos++] = *fmt++;
         }
+
+        if (pos > (size * BUF_SIZE / 2)) {
+            if ((ptr = realloc (s_str, ++size * BUF_SIZE)) == NULL) {
+                return EOF;
+            }
+            s_str = ptr;
+        }
+
         va_end (list);
     }
 
     s_str[pos] = '\0';
+    fputs (s_str, stdout);
+    free (s_str);
 
-    puts (s_str);
     return pos;
 }
 
@@ -65,6 +90,7 @@
 {
     int len;
 
-    len = myprintf ("Bugfix needed: %s\t[%d:%d]", "Lines", 20, 30);
+    len = myprintf ("Printf replacement %% [Version %d - %s]...\n", 5, "LSF Rostock");
+
     return EXIT_SUCCESS;
 }