1 #ifndef __print_h_ 2 #define __print_h_ 3 4 void PRINT (char* fmt, ...); 5 void printch (char ch); 6 V OID printdec (int dec), 7 void Printflt (double flt), 8 void printbin (int bin), 9 void printhex (int hex); printstr (char* str), one-#define CONSOLE_PRINT (CH) Putchar (CH) #endif/ * #ifndef __print_h_ */
#include <stdio.h> 2 #include <stdarg.h> 3 #include "print.h" 4 5 int main (void) 6 {7 print ("Prin T:%c\n ", ' C '); 8 Print ("Print%d\n", 1234567); 9 Print ("Print:%f\n", 1234567.1234567); Print ("Print:%s\n", "string Test"); Print ("Print:%b\n", 0x12345ff); Print ("Print:%x\n", 0xabcdef); Print ("Print:%%\n"); return 0; (char* fmt, ...). {Double Vargflt = 0; int vargint = 0; char* vargpch = NULL; char vargch = 0; char* pfmt = NULL; Va_list VP; Va_start (VP, FMT); PFMT = FMT; while (*pfmt) (*pfmt = = '% ') 34 (* (++PFMT)) {vargch case ' C ': PNs = Va_arg (VP, int); $/* VA_ARG (AP, type), if type is narrow type (char, short, float) A error is given in strict ANS I 39 mode, or a warning otherwise. In non-strict ANSI mode, ' type ' was allowed to being any expression. * * Printch (VARGCH); a break; Case ' d ': Vargint = Va_arg (VP, int); Printdec (Vargint); a break; Case ' f ': Vargflt = Va_arg (VP, double); $/* VA_ARG (AP, type), if type is narrow type (char, short, float) A error is given in strict ANS I-mode, or a warning otherwise. In non-strict ANSI mode, ' type ' was allowed to being any expression. */Wuyi Printflt (Vargflt); a break; The case ' s ': vargpch = Va_arg (VP, char*); Printstr (VARGPCH); a break; The case ' B ': ' B ': Vargint = Va_arg (VP, int); Printbin (Vargint); a break; "X": "x": Vargint = Va_arg (VP, int); Printhex (Vargint); a break; The case '% ': printch ('% '); a break; Default:71 break; pfmt++}; The "Printch" (*pfmt++), the Va_end (VP); Bayi} The Printch (char ch) (c) (console_print) (CH), and the Printdec (int dec) ec==0) 94 Printdec (DEC/10); Printch ((char) (dec%10 + ' 0 ')); 98 void Printflt (double flt) icnt = 0;101 int tmpint = 0;102 103 tmpint = (int) Flt ; 104 Printdec (Tmpint); Printch ('. '); 106 Flt = FLT- tmpint;107 tmpint = (int) (FLT * 1000000); 108 Printdec (Tmpint); 109}110 111 void Printstr (char* str) 112 {113 while (*STR) {printch (*str++);}117}118 119 void Printbin (int bin) + {121 if (bin = = 0) 122 {123 Printstr ("0b") 124 return;125}126 Printbin (BIN/2); 127 Printch ((char) (bin%2 + ' 0 '),}129 printhex (int hex) 131 {hex==0) 133 {134 Printstr ("0x"); 135 return;13 6}137 Printhex (HEX/16) 138 if (Hex <) 139 {Printch (char) (hex%16 + ' 0 ')); 141}142 else143 {144 Printch ((char) (hex%16-10 + ' a ')); 145}146}
printf implementations in the Linux kernel