printf函数源码linux,再来一版简易的printf函数实现
以前發過兩版簡易的串口printf函數實現,最近搞了一段時間Linux的庫文件,回過頭又有不同的理解。
這一版函數基于MSP430F169,%d %x %o %b的實現不再由自己編寫函數,而是調用MSP430-GCC的標準庫函數:
#include
char *itoa(int num, char *str, int radix);
send_fun函數指針,指向調用的UARTx的字節發送函數:
void uart_printf(send_fun fun, char *fmt, ...)
{
char *pnt = (char *)&fmt + sizeof(fmt);
char *str, buf[9];
int radix;
while (*fmt != '\0') {
if (*fmt != '%') {
fun(*fmt);
fmt += 1;
continue;
}
switch (*(fmt + 1)) {
case 'c':
fun(*((int *)pnt));
pnt += sizeof(int);
fmt += 2;
continue;
case 's':
str = (char *)*((int *)pnt);
while (*str != '\0')
fun(*str++);
pnt += sizeof(int);
fmt += 2;
continue;
case 'd':
radix = 10;
goto SEND_NUM;
case 'x':
radix = 16;
goto SEND_NUM;
case 'o':
radix = 8;
goto SEND_NUM;
case 'b':
radix = 2;
goto SEND_NUM;
SEND_NUM:
str = itoa(*(int *)pnt, buf, radix);
while (*str != '\0')
fun(*str++);
pnt += sizeof(int);
fmt += 2;
continue;
default:
break;
}
}
}
實際上,庫stdio.h中也提供了printf的實現,直接調用它們就可以了:
int __attribute__((format (printf, 2, 3))) uprintf(int (*func)(int c), const char *fmt, ...);
總結
以上是生活随笔為你收集整理的printf函数源码linux,再来一版简易的printf函数实现的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: java实验指导书(实验四)答案_jav
- 下一篇: linux自动读取麦克风,检测用户向麦克