stdio.c
2.47 KB
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
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
// CCT compiler with TTC backend
#ifdef __CCT_ttc__
extern int putc(char c);
#define neg(i) -i
#define UINT(i) i
#define _DIGITS "0123456789ABCDEF"
#define _STR "65536"
#endif
// CCT compiler with x86 backend
#ifdef __CCT_x86__
extern int putchar(int c);
#define putc(c) putchar(c)
#define neg(i) -i
#define UINT(i) i
#define _DIGITS "0123456789ABCDEF"
#define _STR "65536"
#endif
// regular compiler
#ifndef __CCT__
extern int putchar(int c);
#define putc(c) putchar(c)
#define neg(i) ~i + 1
#define UINT(i) (unsigned int)(i)
#define _DIGITS _digits
char _digits[17] = "0123456789ABCDEF";
#define _STR _str
char _str[6] = "65536";
#endif
int puts(char *s) {
int n;
int i;
n = 0;
i = 0;
while (1) {
if (s[i]) {
n += putc(s[i]);
i += 1;
} else {
break;
}
}
return n;
}
#define ICHAR 105
#define SCHAR 115
#define UCHAR 117
#define XCHAR 120
#define PERCENT 37
#define MINUS 45
int putu(int u, char f) {
char *DIGITS;
char *str;
int div;
int r;
int n;
int p;
DIGITS = _DIGITS;
str = _STR;
n = 0;
p = 0;
if (f == XCHAR) {
div = 16;
} else {
div = 10;
}
while (u) {
r = u % div;
str[p] = DIGITS[r];
p += 1;
u = u / div;
}
p -= 1;
while (p >= 0) {
n += putc(str[p]);
p -= 1;
}
return n;
}
int puti(int i) {
int n;
int s;
int r;
n = 0;
if (UINT(i) > 32767) {
n += putc(MINUS);
n += putu(neg(i), UCHAR);
return n;
} else {
return putu(i, UCHAR);
}
}
int printf(char *str, ...) {
int n;
int i;
int a;
int *iargs;
char **cargs;
iargs = &str;
cargs = &str;
a = 1;
n = 0;
i = 0;
while (1) {
if (str[i] == 0) {
break;
} else if (str[i] == PERCENT) {
i += 1;
if (str[i] == ICHAR) {
n += puti(iargs[a]);
} else if (str[i] == UCHAR) {
n += putu(iargs[a], UCHAR);
} else if (str[i] == SCHAR) {
n += puts(cargs[a]);
} else if (str[i] == XCHAR) {
n += putu(iargs[a], XCHAR);
} else if (str[i] == PERCENT) {
n += putc(PERCENT);
i += 1;
continue;
} else {
n += putc(PERCENT);
n += putc(str[i]);
}
a += 1;
} else {
n += putc(str[i]);
}
i += 1;
}
return n;
}
int main() {
puts("hello world\n");
puti(42);
puts(" => 42\n");
puti(-42);
puts(" => -42\n");
putu(42, XCHAR);
puts(" => 2A\n");
putu(42, UCHAR);
puts(" => 42\n");
printf("hello %s I'm %u (%x)\n", "stdio", 42, 42);
return 0;
}