-
Notifications
You must be signed in to change notification settings - Fork 0
/
printf.c
110 lines (105 loc) · 2.46 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
#include"minicrt.h"
#define EOF -1
int
fputc(int c, FILE* stream)
{
if(fwrite(&c, 1, 1, stream) != 1) {
return EOF;
}
return c;
}
int
fputs(const char* str, FILE* stream)
{
int len = strlen(str);
if(fwrite((void*)str, 1, len, stream) != len) {
return EOF;
}
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
#include <Windows.h>
#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) {//遇到%d组合
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'://%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);
}