myprintf.c
changeset 62 b7061c0e239f
parent 60 47c13ca8c4d0
child 63 5a82f89d607e
--- a/myprintf.c
+++ b/myprintf.c
@@ -10,7 +10,7 @@
 
 #define BUF_SIZE 1024
 
-int myprintf (char *fmt, ...)
+int myvfprintf (FILE * fp, const char *fmt, va_list list)
 {
     int i, value, pos = 0, size = 1;
     char c;
@@ -20,14 +20,10 @@
     char *s_str;
     char v_str[28];
 
-    va_list list;
-
     if ((s_str = malloc (BUF_SIZE)) == NULL) {
         return EOF;
     }
 
-    va_start (list, fmt);
-
     while (*fmt) {
         switch (*fmt) {
         case '%':
@@ -42,7 +38,7 @@
                 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... */
+                        fputs (s_str, fp);  /* print it anyway... */
                         return EOF;
                     }
                     s_str = ptr;
@@ -75,17 +71,41 @@
             }
             s_str = ptr;
         }
-
-        va_end (list);
     }
 
+    va_end (list);
+
     s_str[pos] = '\0';
-    fputs (s_str, stdout);
+    fputs (s_str, fp);
     free (s_str);
 
     return pos;
 }
 
+int myfprintf (FILE * fp, const char *fmt, ...)
+{
+    va_list list;
+    int ret;
+
+    va_start (list, fmt);
+    ret = myvfprintf (fp, fmt, list);
+    va_end (list);
+
+    return ret;
+}
+
+int myprintf (const char *fmt, ...)
+{
+    va_list list;
+    int ret;
+
+    va_start (list, fmt);
+    ret = myvfprintf (stdout, fmt, list);
+    va_end (list);
+
+    return ret;
+}
+
 int main (int argc, char **argv)
 {
     int len;