00001
00006
00007
00008
00009
00010
00011
00012
00013
00014
00015
00016
00017
00018
00019
00020
00021
00022
00023
00024
00025 #include <stdarg.h>
00026
00027 static const char hexdigits[] = "0123456789ABCDEF";
00028 static const char lhexdigits[] = "0123456789abcdef";
00029 static const char empty_string[] = "(null string)";
00030
00031
00032
00033
00034
00035
00036
00037
00038 static int itoa(unsigned int value, char *dst, int pos, int len,
00039 int radix, const char *digits)
00040 {
00041 char sbuf[10];
00042 int spos;
00043
00044 spos = 0;
00045 while(value) {
00046 sbuf[spos] = value % radix;
00047 spos++;
00048 value /= radix;
00049 }
00050 if(!spos)
00051 *sbuf = 0, spos = 1;
00052
00053 for(spos--; pos<len && spos>=0; pos++,spos--) {
00054 dst[pos] = digits[(int)sbuf[spos]];
00055 }
00056
00057 return pos-1;
00058 }
00059
00060
00061
00062
00063
00064
00065
00066
00067
00068
00069
00070
00071
00072
00073
00074 int vsnprintf(char *dst, int len, const char *fmt, va_list arg)
00075 {
00076 int pos;
00077 int cc;
00078 const char *temp;
00079 unsigned int scratch;
00080
00081 for(pos=0, cc=0; (pos<len) && (cc=*fmt); pos++, fmt++) {
00082 if(cc!='%')
00083 dst[pos] = cc;
00084 else {
00085 cc = *(++fmt);
00086 switch(cc) {
00087 case 'd':
00088 case 'i':
00089
00090 scratch = va_arg(arg, unsigned);
00091 pos = itoa(scratch, dst, pos, len, 10,
00092 hexdigits);
00093 break;
00094 case 'X':
00095
00096 scratch = va_arg(arg, unsigned);
00097 pos = itoa(scratch, dst, pos, len, 16,
00098 hexdigits);
00099 break;
00100 case 'x':
00101
00102 scratch = va_arg(arg, unsigned);
00103 pos = itoa(scratch, dst, pos, len, 16,
00104 lhexdigits);
00105 break;
00106 case 's':
00107
00108 temp = va_arg(arg, const char*);
00109 if(!temp)
00110 temp = empty_string;
00111 for(; pos<len && *temp; pos++, temp++) {
00112 dst[pos] = *temp;
00113 }
00114 pos--;
00115 break;
00116 case 'c':
00117
00118 dst[pos] = va_arg(arg, int);
00119 break;
00120 case '\0':
00121 case '%':
00122 dst[pos] = cc;
00123 break;
00124 }
00125
00126 if(!cc) {
00127 break;
00128 }
00129 }
00130 }
00131
00132 dst[pos++] = '\0';
00133
00134 return pos;
00135 }
00136
00137
00138
00139
00140
00141 char *snprintf(char *dst, int len, const char *fmt, ...)
00142 {
00143 va_list arg;
00144
00145 va_start(arg, fmt);
00146 (void) vsnprintf(dst, len, fmt, arg);
00147 va_end(arg);
00148
00149 return dst;
00150 }
00151