printf.c (1467B)
1 #include <stdarg.h> 2 3 #include "types.h" 4 #include "stat.h" 5 #include "user.h" 6 7 static void 8 putc(int fd, char c) 9 { 10 write(fd, &c, 1); 11 } 12 13 static void 14 printint(int fd, int xx, int base, int sgn) 15 { 16 static char digits[] = "0123456789ABCDEF"; 17 char buf[16]; 18 int i, neg; 19 uint x; 20 21 neg = 0; 22 if(sgn && xx < 0){ 23 neg = 1; 24 x = -xx; 25 } else { 26 x = xx; 27 } 28 29 i = 0; 30 do{ 31 buf[i++] = digits[x % base]; 32 }while((x /= base) != 0); 33 if(neg) 34 buf[i++] = '-'; 35 36 while(--i >= 0) 37 putc(fd, buf[i]); 38 } 39 40 // Print to the given fd. Only understands %d, %x, %p, %s. 41 void 42 printf(int fd, char *fmt, ...) 43 { 44 va_list ap; 45 char *s; 46 int c, i, state; 47 va_start(ap, fmt); 48 49 state = 0; 50 for(i = 0; fmt[i]; i++){ 51 c = fmt[i] & 0xff; 52 if(state == 0){ 53 if(c == '%'){ 54 state = '%'; 55 } else { 56 putc(fd, c); 57 } 58 } else if(state == '%'){ 59 if(c == 'd'){ 60 printint(fd, va_arg(ap, int), 10, 1); 61 } else if(c == 'x' || c == 'p'){ 62 printint(fd, va_arg(ap, int), 16, 0); 63 } else if(c == 's'){ 64 s = va_arg(ap, char*); 65 if(s == 0) 66 s = "(null)"; 67 while(*s != 0){ 68 putc(fd, *s); 69 s++; 70 } 71 } else if(c == 'c'){ 72 putc(fd, va_arg(ap, uint)); 73 } else if(c == '%'){ 74 putc(fd, c); 75 } else { 76 // Unknown % sequence. Print it to draw attention. 77 putc(fd, '%'); 78 putc(fd, c); 79 } 80 state = 0; 81 } 82 } 83 }