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