6 static void bwrite(char *buf, size_t buf_sz, char *str, int sz);
7 static int intern_printf(char *buf, size_t sz, const char *fmt, va_list ap);
15 int puts(const char *s)
24 /* -- printf and friends -- */
26 static char *convc = "dioxXucsfeEgGpn%";
28 #define IS_CONV(c) strchr(convc, c)
30 int printf(const char *fmt, ...)
36 res = intern_printf(0, 0, fmt, ap);
41 int vprintf(const char *fmt, va_list ap)
43 return intern_printf(0, 0, fmt, ap);
46 int sprintf(char *buf, const char *fmt, ...)
52 res = intern_printf(buf, 0, fmt, ap);
57 int vsprintf(char *buf, const char *fmt, va_list ap)
59 return intern_printf(buf, 0, fmt, ap);
62 int snprintf(char *buf, size_t sz, const char *fmt, ...)
68 res = intern_printf(buf, sz, fmt, ap);
73 int vsnprintf(char *buf, size_t sz, const char *fmt, va_list ap)
75 return intern_printf(buf, sz, fmt, ap);
79 /* intern_printf provides all the functionality needed by all the printf
81 * - buf: optional buffer onto which the formatted results are written. If null
82 * then the output goes to the terminal through putchar calls. This is used
83 * by the (v)sprintf variants which write to an array of char.
84 * - sz: optional maximum size of the output, 0 means unlimited. This is used
85 * by the (v)snprintf variants to avoid buffer overflows.
86 * The rest are obvious, format string and variable argument list.
89 #define BUF(x) ((x) ? (x) + cnum : (x))
90 #define SZ(x) ((x) ? (x) - cnum : (x))
92 static int intern_printf(char *buf, size_t sz, const char *fmt, va_list ap)
97 const char *fstart = 0;
106 int left_align = 0; /* not implemented yet */
127 bwrite(BUF(buf), SZ(sz), "0x", 2);
138 bwrite(BUF(buf), SZ(sz), "0", 1);
145 utoa(va_arg(ap, unsigned int), conv_buf, base);
147 itoa(va_arg(ap, int), conv_buf, base);
150 for(i=0; conv_buf[i]; i++) {
151 conv_buf[i] = toupper(conv_buf[i]);
155 slen = strlen(conv_buf);
156 for(i=slen; i<fwidth; i++) {
157 bwrite(BUF(buf), SZ(sz), (char*)&padc, 1);
161 bwrite(BUF(buf), SZ(sz), conv_buf, strlen(conv_buf));
167 char c = va_arg(ap, int);
168 bwrite(BUF(buf), SZ(sz), &c, 1);
174 str = va_arg(ap, char*);
177 for(i=slen; i<fwidth; i++) {
178 bwrite(BUF(buf), SZ(sz), (char*)&padc, 1);
181 bwrite(BUF(buf), SZ(sz), str, slen);
186 *va_arg(ap, int*) = cnum;
193 /* restore default conversion state */
226 const char *fw = fmt;
227 while(*fmt && isdigit(*fmt)) fmt++;
236 bwrite(BUF(buf), SZ(sz), (char*)fmt++, 1);
245 /* bwrite is called by intern_printf to transparently handle writing into a
246 * buffer (if buf is non-null) or to the terminal (if buf is null).
248 static void bwrite(char *buf, size_t buf_sz, char *str, int sz)
251 if(buf_sz && buf_sz <= sz) sz = buf_sz - 1;
252 memcpy(buf, str, sz);
257 for(i=0; i<sz; i++) {