-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathstdio.c
More file actions
114 lines (99 loc) · 2.56 KB
/
stdio.c
File metadata and controls
114 lines (99 loc) · 2.56 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
#pragma warning(push)
#pragma warning(push, 0)
#include <stdarg.h>
typedef signed char int8_t;
typedef short int16_t;
typedef int int32_t;
typedef long long int64_t;
typedef unsigned char uint8_t;
typedef unsigned short uint16_t;
typedef unsigned int uint32_t;
typedef unsigned long long uint64_t;
static void reverse(char* str, int len) {
int i = 0, j = len - 1;
while (i < j) {
char tmp = str[i];
str[i] = str[j];
str[j] = tmp;
i++; j--;
}
}
static int itoa_simple(int64_t value, char* str, int base) {
char* ptr = str;
int is_negative = 0;
if (value == 0) {
*ptr++ = '0';
*ptr = '\0';
return 1;
}
if (base == 10 && value < 0) {
is_negative = 1;
value = -value;
}
while (value != 0) {
int rem = (uint64_t)value % base;
*ptr++ = (rem > 9) ? (rem - 10 + 'a') : (rem + '0');
value /= base;
}
if (is_negative) *ptr++ = '-';
*ptr = '\0';
reverse(str, ptr - str);
return ptr - str;
}
int my_vsprintf(char* buffer, const char* format, va_list args)
{
char* buf_ptr = buffer;
const char* p = format;
while (*p) {
if (*p != '%') {
*buf_ptr++ = *p++;
continue;
}
p++;
if (*p == 'd') {
int val = va_arg(args, int);
char numbuf[32];
int len = itoa_simple(val, numbuf, 10);
for (int i = 0; i < len; i++) *buf_ptr++ = numbuf[i];
}
else if (*p == 'x') {
int val = va_arg(args, int);
char numbuf[32];
int len = itoa_simple(val, numbuf, 16);
for (int i = 0; i < len; i++) *buf_ptr++ = numbuf[i];
}
else if (*p == 's') {
char* s = va_arg(args, char*);
while (*s) *buf_ptr++ = *s++;
}
else if (*p == 'c') {
char c = (char)va_arg(args, int);
*buf_ptr++ = c;
}
else {
*buf_ptr++ = *p;
}
p++;
}
*buf_ptr = '\0';
return buf_ptr - buffer;
}
int my_strcmp(const char* str1, const char* str2)
{
while (*str1 && (*str1 == *str2)) {
str1++;
str2++;
}
return *(unsigned char*)str1 - *(unsigned char*)str2;
}
int my_strncmp(const char* str1, const char* str2, size_t n)
{
while (n && *str1 && (*str1 == *str2)) {
str1++;
str2++;
n--;
}
if (n == 0) return 0;
return *(unsigned char*)str1 - *(unsigned char*)str2;
}
#pragma warning(pop)