昨天,我發表了一篇用可變參實現的fprintf函數,其實說實話還不完全是可變參實現的,因為用到了FILE * 這樣的指針,需要包含stdio.h這個頭文件才能實現這個函數,今天我們就來看看,如何拋棄stdio.h,全0開始實現printf , sprintf ,當然,這段代碼是我在linux內核裡面獲取的,再經過我本人修改,移植,在DevC++這個編譯環境中通過測試。我們來看看代碼:
#include運行結果:#define NULL 0 //如果字符串中為數字,則返回數字 static int skip_atoi(const char **s) { int i = 0; while (isdigit(**s)) i = i * 10 + *((*s)++) - '0'; return i; } static inline int isdigit(int ch) { return (ch >= '0') && (ch <= '9'); //返回從字符中提取0-9的數字 } #define ZEROPAD 1 /* pad with zero */ #define SIGN 2 /* unsigned/signed long */ #define PLUS 4 /* show plus */ #define SPACE 8 /* space if plus */ #define LEFT 16 /* left justified */ #define SMALL 32 /* Must be 32 == 0x20 */ #define SPECIAL 64 /* 0x */ //這個宏主要用來實現判斷是要轉化成什麼進制數 #define __do_div(n, base) ({ \ int __res; \ __res = ((unsigned long) n) % (unsigned) base; \ n = ((unsigned long) n) / (unsigned) base; \ __res; }) static char *number(char *str, long num, int base, int size, int precision, int type) { /*這個字符串數組存放著0-15這16個數字,到時候要用來進制轉換*/ static const char digits[16] = "0123456789ABCDEF"; char tmp[66]; char c, sign, locase; int i; /*locase = 0 或者 0x20 , 產生與locase相同的數字或字母,也許字母是小寫的*/ locase = (type & SMALL); if (type & LEFT) type &= ~ZEROPAD; if (base < 2 || base > 36) return NULL; c = (type & ZEROPAD) ? '0' : ' '; sign = 0; if (type & SIGN) { if (num < 0) { sign = '-'; num = -num; size--; } else if (type & PLUS) { sign = '+'; size--; } else if (type & SPACE) { sign = ' '; size--; } } //檢測進制數,是要2進制還是要8進制還是16進制 if (type & SPECIAL) { if (base == 16) size -= 2; else if (base == 8) size--; } i = 0; if (num == 0) tmp[i++] = '0'; else while (num != 0) tmp[i++] = (digits[__do_div(num, base)] | locase); if (i > precision) precision = i; size -= precision; if (!(type & (ZEROPAD + LEFT))) while (size-- > 0) *str++ = ' '; if (sign) *str++ = sign; if (type & SPECIAL) { if (base == 8) *str++ = '0'; else if (base == 16) { *str++ = '0'; *str++ = ('X' | locase); } } if (!(type & LEFT)) while (size-- > 0) *str++ = c; while (i < precision--) *str++ = '0'; while (i-- > 0) *str++ = tmp[i]; while (size-- > 0) *str++ = ' '; return str; } int vsprintf(char *buf, const char *fmt, va_list args) { int len; unsigned long num; int i, base; char *str; const char *s; int flags; int field_width; /*位寬輸出*/ int precision; int qualifier; //這裡判斷,如果在字符串fmt中不存在%這個符號,那麼字符串繼續往後遍歷 for (str = buf; *fmt; ++fmt) { if (*fmt != '%') { *str++ = *fmt; continue; } //程序設置標志位 flags = 0; repeat: ++fmt; /* this also skips first '%' */ //格式控制 switch (*fmt) { case '-': flags |= LEFT; goto repeat; case '+': flags |= PLUS; goto repeat; case ' ': flags |= SPACE; goto repeat; case '#': flags |= SPECIAL; goto repeat; case '0': flags |= ZEROPAD; goto repeat; } //獲取寬度,這裡主要是要實現printf的位寬機制 field_width = -1; if (isdigit(*fmt)) field_width = skip_atoi(&fmt); else if (*fmt == '*') { ++fmt; field_width = va_arg(args, int); if (field_width < 0) { field_width = -field_width; flags |= LEFT; } } precision = -1; if (*fmt == '.') { ++fmt; if (isdigit(*fmt)) precision = skip_atoi(&fmt); else if (*fmt == '*') { ++fmt; precision = va_arg(args, int); } if (precision < 0) precision = 0; } /*得到的轉換限定符*/ qualifier = -1; if (*fmt == 'h' || *fmt == 'l' || *fmt == 'L') { qualifier = *fmt; ++fmt; } /*默認進制為10進制*/ base = 10; //以下主要是要實現printf的格式輸出 例如:%d , %c , %u ...等等 switch (*fmt) { case 'c': //以字符形式進行輸出 if (!(flags & LEFT)) while (--field_width > 0) *str++ = ' '; *str++ = (unsigned char)va_arg(args, int); while (--field_width > 0) *str++ = ' '; continue; case 's': //以字符串形式進行輸出 s = va_arg(args, char *); len = strnlen(s, precision); if (!(flags & LEFT)) while (len < field_width--) *str++ = ' '; for (i = 0; i < len; ++i) *str++ = *s++; while (len < field_width--) *str++ = ' '; continue; case 'p': //以地址形式輸出,也就是以16進制數輸出 if (field_width == -1) { field_width = 2 * sizeof(void *); flags |= ZEROPAD; } str = number(str, (unsigned long)va_arg(args, void *), 16, field_width, precision, flags); continue; case 'n': if (qualifier == 'l') { long *ip = va_arg(args, long *); *ip = (str - buf); } else { int *ip = va_arg(args, int *); *ip = (str - buf); } continue; case '%': //這裡表示字符串中存在%號這個字符 *str++ = '%'; continue; /* integer number formats - set up the flags and "break" */ case 'o': //%o 表示8進制輸出 base = 8; break; case 'x': //%x或者%X 表示16進制輸出 flags |= SMALL; case 'X': base = 16; break; case 'd': //%d %i整形數輸出,%u無符號整形 case 'i': flags |= SIGN; case 'u': break; default: *str++ = '%'; if (*fmt) *str++ = *fmt; else --fmt; continue; } if (qualifier == 'l') //以無符號長整型輸出 num = va_arg(args, unsigned long); else if (qualifier == 'h') { num = (unsigned short)va_arg(args, int); if (flags & SIGN) num = (short)num; } else if (flags & SIGN) num = va_arg(args, int); else num = va_arg(args, unsigned int); str = number(str, num, base, field_width, precision, flags); } *str = '\0'; //字符串遍歷到有\0的地方就停止 return str - buf; } //可變參形式實現sprintf int mysprintf(char *buf, const char *fmt, ...) { va_list args; int i; va_start(args, fmt); //將獲取到的fmt格式字符串寫入到buf這個緩存裡去 i = vsprintf(buf, fmt, args); //釋放args va_end(args); return i; } //可變參形式進行實現myprintf int myprintf(const char *fmt, ...) { char printf_buf[1024]; va_list args; int printed; va_start(args, fmt); printed = vsprintf(printf_buf, fmt, args); va_end(args); puts(printf_buf); return printed; } int main(void) { myprintf("輸出字符串:hello world!\n") ; static int sum , a = 3 , b = 4; sum = a + b ; myprintf("sum(十進制輸出):%d\n",sum); myprintf("sum(16進制輸出):%p\n",sum); char buffer[128] = {0}; //將字符串存到一個數組buffer裡去 mysprintf(buffer , "輸出字符串:hello world!\n"); //以字符串格式輸出這個buffer的內容 myprintf("buffer:%s\n",buffer); return 0 ; }
看完代碼就知道了,我們這個程序沒有包含stdio.h這個頭文件,一樣也就實現了printf和sprintf這兩個函數。這樣的話,以後如果要自己實現一個printf函數,這份代碼就可以作為一個文件來進行調用了,哈哈!