继续扩展myprint的功能为操作系统开发加油!
作者:互联网
这段代码虽然不免抄袭大侠们的嫌疑,但是完全是自己重新写过的,没有知识产权的纠纷了,而且更容易看懂,今天真是收获不小。
#include <stdio.h>
char str[0xff];
void str_cpy(const char* s, char* d) {
while(*s)
*d++ = *s++;
*d = '\0';
return;
}
int str_len(const char* s) {
int len = 0;
while(*s++)
len++;
return len;
}
int mydiv(int* x, int y) {
if(y == 0)
return -*x;
int tmp;
tmp = *x % y;
*x /= y;
return tmp;
}
char* myitoa(int x, int d){
static char mystr[0x20];
char tmp[0x20];
const char* c = "0123456789abcdef";
int y, i = 0, j;
while(x) {
y = mydiv(&x, d);
tmp[i++] = c[y];
}
tmp[i] = '\0';
j = str_len(tmp);
for(i = 0; i < str_len(tmp); i++){
mystr[i] = tmp[--j];
}
mystr[i] = '\0';
return mystr;
}
void myprintf(const char* s, ...){
char* mystr = str;
char* tmp;
char** varg = (char**)&s;
varg++;
char c;
int len;
while(c = *s) {
if('%' != c) {
*mystr++ = c;
s++;
} else {
s++;
switch(c = *s) {
case '%':
s++;
*mystr++ = '%';
break;
case 'c':
s++;
*mystr++ = *((char*)varg);
varg++;
break;
case 's':
s++;
str_cpy(*varg, mystr);
len = str_len(str);
mystr = str + len;
varg++;
break;
case 'x':
s++;
tmp = myitoa(*((int*)varg), 16);
*mystr++ = '0';
*mystr++ = 'x';
str_cpy(tmp, mystr);
len = str_len(str);
mystr = str + len;
varg++;
break;
case 'd':
s++;
tmp = myitoa(*((int*)varg), 10);
str_cpy(tmp, mystr);
len = str_len(str);
mystr = str + len;
varg++;
break;
case 'b':
s++;
tmp = myitoa(*((int*)varg), 2);
str_cpy(tmp, mystr);
len = str_len(str);
mystr = str + len;
*mystr++ = 'b';
*mystr = '\0';
varg++;
break;
default:
break;
}
}
}
}
int main(void) {
myprintf("He%%%llo, %%%%World!\n%s, %c, %b, %s, %d, %s, %x", "How", '@',
0xff, "YOU", 15, "Wel%come!", 128);
printf("%s", str);
}
标签:tmp,操作系统,myprint,len,char,++,str,mystr,加油 来源: https://blog.csdn.net/weixin_39410618/article/details/89502252