equal
deleted
inserted
replaced
8 #include <stdarg.h> |
8 #include <stdarg.h> |
9 #include <string.h> |
9 #include <string.h> |
10 |
10 |
11 #define BUF_SIZE 1024 |
11 #define BUF_SIZE 1024 |
12 |
12 |
13 int myprintf (char *fmt, ...) |
13 int myvfprintf (FILE * fp, const char *fmt, va_list list) |
14 { |
14 { |
15 int i, value, pos = 0, size = 1; |
15 int i, value, pos = 0, size = 1; |
16 char c; |
16 char c; |
17 |
17 |
18 char *ptr; |
18 char *ptr; |
19 char *s; |
19 char *s; |
20 char *s_str; |
20 char *s_str; |
21 char v_str[28]; |
21 char v_str[28]; |
22 |
22 |
23 va_list list; |
|
24 |
|
25 if ((s_str = malloc (BUF_SIZE)) == NULL) { |
23 if ((s_str = malloc (BUF_SIZE)) == NULL) { |
26 return EOF; |
24 return EOF; |
27 } |
25 } |
28 |
|
29 va_start (list, fmt); |
|
30 |
26 |
31 while (*fmt) { |
27 while (*fmt) { |
32 switch (*fmt) { |
28 switch (*fmt) { |
33 case '%': |
29 case '%': |
34 switch (*++fmt) { |
30 switch (*++fmt) { |
40 case 's': |
36 case 's': |
41 s = va_arg (list, char *); |
37 s = va_arg (list, char *); |
42 while ((pos + strlen (s)) > (size * BUF_SIZE)) { |
38 while ((pos + strlen (s)) > (size * BUF_SIZE)) { |
43 if ((ptr = realloc (s_str, ++size * BUF_SIZE)) == NULL) { |
39 if ((ptr = realloc (s_str, ++size * BUF_SIZE)) == NULL) { |
44 s_str[pos] = '\0'; |
40 s_str[pos] = '\0'; |
45 fputs (s_str, stdout); /* print it anyway... */ |
41 fputs (s_str, fp); /* print it anyway... */ |
46 return EOF; |
42 return EOF; |
47 } |
43 } |
48 s_str = ptr; |
44 s_str = ptr; |
49 } |
45 } |
50 for (i = 0; i < strlen (s); i++) { |
46 for (i = 0; i < strlen (s); i++) { |
73 if ((ptr = realloc (s_str, ++size * BUF_SIZE)) == NULL) { |
69 if ((ptr = realloc (s_str, ++size * BUF_SIZE)) == NULL) { |
74 return EOF; |
70 return EOF; |
75 } |
71 } |
76 s_str = ptr; |
72 s_str = ptr; |
77 } |
73 } |
78 |
|
79 va_end (list); |
|
80 } |
74 } |
81 |
75 |
|
76 va_end (list); |
|
77 |
82 s_str[pos] = '\0'; |
78 s_str[pos] = '\0'; |
83 fputs (s_str, stdout); |
79 fputs (s_str, fp); |
84 free (s_str); |
80 free (s_str); |
85 |
81 |
86 return pos; |
82 return pos; |
|
83 } |
|
84 |
|
85 int myfprintf (FILE * fp, const char *fmt, ...) |
|
86 { |
|
87 va_list list; |
|
88 int ret; |
|
89 |
|
90 va_start (list, fmt); |
|
91 ret = myvfprintf (fp, fmt, list); |
|
92 va_end (list); |
|
93 |
|
94 return ret; |
|
95 } |
|
96 |
|
97 int myprintf (const char *fmt, ...) |
|
98 { |
|
99 va_list list; |
|
100 int ret; |
|
101 |
|
102 va_start (list, fmt); |
|
103 ret = myvfprintf (stdout, fmt, list); |
|
104 va_end (list); |
|
105 |
|
106 return ret; |
87 } |
107 } |
88 |
108 |
89 int main (int argc, char **argv) |
109 int main (int argc, char **argv) |
90 { |
110 { |
91 int len; |
111 int len; |