-
Notifications
You must be signed in to change notification settings - Fork 3
/
printf.c
130 lines (107 loc) · 1.93 KB
/
printf.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
#include "minicrt.h"
int fputc(int c, FILE* stream)
{
if(fwrite(&c,1,1,stream) != 1)
{
return EOF;
}else{
return c;
}
}
int fputs(const char* str, FILE * stream)
{
int len = strlen(str);
if(fwrite(str, 1, len, stream) != len)
{
return EOF;
}else{
return len;
}
}
#ifndef WIN32
#define va_list char*
#define va_start(ap,arg) (ap=(va_list)&arg + sizeof(arg))
#define va_arg(ap,t) (*(t*)((ap+=sizeof(t)) - sizeof(t)))
#define va_end(ap) (ap=(va_list)0)
#else
#endif
int vfprintf(FILE* stream, const char* format, va_list arglist)
{
int translating = 0;
int ret = 0;
const char* p=0;
for( p = format; *p!='\0'; ++p)
{
switch(*p)
{
case '%':
if(!translating)
{
translating=1;
}
else
{
if(fputc('%', stream) < 0)
{
return EOF;
}
++ret;
translating = 0;
}
break;
case 'd':
if(translating)
{
char buf[16];
translating = 0;
itoa(va_arg(arglist,int), buf, 10);
if(fputs(buf, stream) < 0)
{
return EOF;
}
ret += strlen(buf);
}else if(fputc('d', stream) < 0)
{
return EOF;
}else
++ret;
break;
case 's':
if(translating)
{
const char* str = va_arg(arglist, const char*);
translating = 0;
if(fputs(str, stream) < 0)
return EOF;
ret += strlen(str);
}else if(fputc('s', stream) <0)
{
return EOF;
}else
++ret;
break;
default:
if(translating)
translating = 0;
if(fputc(*p, stream) < 0)
{
return EOF;
}else
++ret;
break;
}
}
return ret;
}
int printf(const char *format, ...)
{
va_list(arglist);
va_start(arglist, format);
return vfprintf(stdout, format, arglist);
}
int fprintf(FILE* stream, const char* format, ...)
{
va_list(arglist);
va_start(arglist, format);
return vfprintf(stream, format, arglist);
}